let obj1 = {
a: 1,
foo: () => {
console.log(this.a)
}
}
obj1.foo()//问题1
const obj2 = obj1.foo
obj2()//问题2
答案:两个都是undefined。
let obj1 = {
a: 1,
foo: function () {
console.log(this.a);
}
}
obj1.foo()//?
const obj2 = obj1.foo
obj2()//?
答案:1和undefined。
- 普通函数的this指向:
1.普通函数的this总是指向它的直接调用者。
2.在严格模式下,没找到直接调用者,则函数中的this是undefined。
3.在默认模式下(非严格模式),没找到直接调用者,则函数中的this指向window。
- 箭头函数的this指向:
1.没有this指向,this永远来自其上下文的 this;
2.任何方法都改变不了其指向,如call(), bind(), apply();
3.箭头函数不能用作构造器,和 new一起用会抛出错误
4.箭头函数没有prototype(原型)属性
5.不绑定arguments,该对象在函数体内不存在,如果要用的话,可以用rest参数代替;
6.箭头函数和匿名函数是有区别的(this指向的不同)。
普通匿名函数与箭头函数 this 区别
var obj1 = {
count: 1,
getCount: function (y) {
console.log(this); //{count: 1, getCount: ƒ}
let fn = function (y) {
console.log(this); //Window
return y + this.count;
}
return fn(y);
}
}
console.log(obj1.getCount(6));//NaN
//getCount是普通函数,this指向调用它的对象,
//fn是匿名函数,this指向Window。
var obj2 = {
count: 2,
getCount: function (y) {
console.log(this); //{count: 2, getCount: ƒ}
let fn = (y) => {
console.log(this); //{count: 2, getCount: ƒ}
return y - this.count;
}
return fn(y);
}
}
console.log(obj2.getCount(6));//4
//getCount是普通函数,this指向调用它的对象,
//fn是箭头函数,this指向包着他的函数的this。