yxfanxiao / yxfanxiao.github.io

My Blog Space
3 stars 0 forks source link

JS: this关键字及判断 #10

Open yxfanxiao opened 8 years ago

yxfanxiao commented 8 years ago

JS中的this

When a function of an object was called, the object will be passed into the execution context as this value.

function中的this永远指向调用它的对象,因此有5步判断法:

  1. 是否是new关键字创建的对象
  2. 是否有bind绑定
  3. 是否有apply、call
  4. 是否是Object的方法
  5. 全局(window | global)

要知道,this是个参数,普通的函数隐式传入它,而apply、call、bind显示指定它。


ES6中的arrow function, 函数内置this的值,取决于函数在哪里定义(继承外围作用域),而非函数的上下文环境。且this不可变。

var obj = {};
obj.fun1 = function() {
    setTimeout(() => {
        console.log(this);      // this: obj
    }, 1000)
}
obj.fun1()
obj.fun2 = () => {
    setTimeout(() => {
        console.log(this);      // this: window
    }, 1000)
}
obj.fun2()

var o = {};
o.f = function() {
    console.log(this);          // o
    (()=>{
        console.log(this)       // o
    })()
}
o.f()

bind和apply、call的区别?

之前用的很自然,竟没有想过什么区别....

    代码运行到apply、call时,方法立刻执行,this指向第一个参数;
    而bind并不会被立刻执行,只是返回一个被绑定的函数指针(this指向第一个参数)。