美文网首页
JavaScript中的this

JavaScript中的this

作者: 西域战神 | 来源:发表于2019-01-11 22:59 被阅读0次

this 是一个很特别的关键字,被自定义在左右函数的作用域中,我们先来看下函数的调用。
js里有三种函数的调用形式:

fn ( param1, param2)  
obj.method(param1, param2)
fn.call(context, param1, param2)

前面两种是call的语法糖,转换为call

fn.call(undefined, param1, param2)
obj.method.call(obj, param1, param2)

这样我们可以很清楚的知道, this就是上面的context。
当你写下如下代码时:

function fn () {
  console.log(this)
}
fn ()

等价于

function fn () {
  console.log(this)
}
fn.call(undefined)

由于浏览器规定,如果call的第一个参数为null或者undefined,那么call的第一个参数是window,在strict模式下,call的第一个参数默认是undefined。我们再来看一个在对象中调用方法的例子

let human = {
    name: 'sss',
    age: 24,
    introduceSelf (person) {
        console.log(`I am ${person.name}, ${person.age} years old`)
    }
}
human.introduceSelf({name:'Emily', age: 24}) // I am emily, 24 years old
human.introduceSelf(person) //I am sss, 24 years old

此时我们将human自身作为参数传递给了introduceSelf函数,这样使用太过啰嗦,我们可以做下面的改变:

let human = {
    name: 'sss',
    age: 24,
    introduceSelf () {
        console.log(`I am ${this.name}, ${this.age} years old`)
    }
}
human.introduceSelf() //I am sss, 24 years old

此时我们通过this达到了调用自身属性的目的,human对象的name和age是默认值。但是如果我们做如下改变

let introduce = human.introduceSelf
introduce () // I am , undefined years old

由于此时this是window,我们并没有获取我们预期的效果。上面的函数调用方法等同于:

introduce.call ( undefined )
const Emily = { name: 'Emily', age: 24 }
human.introduceSelf.call(emily) // I am Emily, 24 years old

总结

this是call一个函数时,传入的第一个参数。或者是某个对象调用它的方法,那么该方法的this就是该对象( 对象不存在时,非严格模式下默认是 window, 严格模式下是undefined)。

相关文章

  • 1body中添加js

    1 中的 JavaScript JavaScript 函数和事件上面例子中的 JavaScript 语句,会...

  • JS中的类型转换

    JavaScript 中的类型转换 JavaScript 基本数据类型 JavaScript 中的一共有 8 中内...

  • js中的this

    javascript中的this javascript中的this与java中的this有点不同。ECMAScri...

  • JavaScript中的字符串

    @(javascript)[js字符串][toc] JavaScript中的字符串 字符串是JavaScript中...

  • 06-JavaScript数组和函数

    JavaScript数组 JavaScript中的数组可以存储不同类型的数据 JavaScript中的数组是引用类...

  • Client's JavaScript

    什么是JavaScript? JavaScript的运行环境? 浏览器中JavaScript可以做什么? 浏览器中...

  • javascript中的this

    一般说到JS的this,都会想起在函数中变来变去的this。但是事情的发生都是有规则的约束,JS中的this也不例...

  • JavaScript中的this

    什么是this? 首先对this的下个定义:this是在执行上下文创建时确定的一个在执行过程中不可更改的变量。th...

  • JavaScript中的this

    JavaScript中的this很容易让人迷惑,但弄清楚后其实还是很好区分的。JavaScript中的this总是...

  • javascript中的this

    在javascript中的this大致可以理解成谁调用的this就指向谁 全局环境中的this 函数中的this ...

网友评论

      本文标题:JavaScript中的this

      本文链接:https://www.haomeiwen.com/subject/rwufdqtx.html