Open yxfanxiao opened 8 years ago
When a function of an object was called, the object will be passed into the execution context as this value.
function中的this永远指向调用它的对象,因此有5步判断法:
要知道,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指向第一个参数)。
JS中的this
function中的this永远指向调用它的对象,因此有5步判断法:
ES6中的arrow function, 函数内置this的值,取决于函数在哪里定义(继承外围作用域),而非函数的上下文环境。且this不可变。
之前用的很自然,竟没有想过什么区别....