this到底指向哪里?
this指向问题就看一点就行,this 的值就是在点之前的这个对象,即调用该方法的对象。
在没有对象的情况下调用:this == undefined
function sayHi() {
alert(this);
}
sayHi(); // undefined
在这种情况下,严格模式下的 this 值为 undefined。如果我们尝试访问 this.name,将会报错。
在非严格模式的情况下,this 将会是 全局对象(浏览器中的 window)。这是一个历史行为,“use strict” 已经将其修复了。
通常这种调用是程序出错了。如果在一个函数内部有 this,那么通常意味着它是在对象上下文环境中被调用的。
其他
- 存储在对象属性中的函数被称为“方法”。
- 方法允许对象进行像 object.doSomething() 这样的“操作”。
- 方法可以将对象引用为 this。
this 的值是在程序运行时得到的。
- 一个函数在声明时,可能就使用了 this,但是这个 this 只有在函数被调用时才会有值。
- 可以在对象之间复制函数。
- 以“方法”的语法调用函数时:object.method(),调用过程中的 this 值是 object。
- 请注意箭头函数有些特别:它们没有 this。在箭头函数内部访问到的 this 都是从外部获取的。
链式调用
let ladder={
index:0,
up(){
this.index++;
return this;
},
down(){
this.index--;
return this;
},
alert(){
alert(this.index);
return this;
}
}
ladder.up().up().down().alert(); // 1
在对象字面量中使用 “this”
function makeUser() {
return {
name: "John",
ref: this
};
};
let user = makeUser();
alert( user.ref.name ) // Error: Cannot read property 'name' of undefined
这是因为设置 this
的规则不考虑对象定义。只有调用那一刻才重要,而且this
的值是对于整个函数的,代码段和对象字面量对它都没有影响。
这里 makeUser() 中的 this 的值是 undefined,因为它是被作为函数makeUser()
调用的,而不是通过点符号被作为方法调用。
所以 ref: this
实际上取的是当前函数makeUser()
的this
。
上面等同于
function makeUser() {
return this;
};
alert( makeUser().name )
那么正确的呢?
function makeUser() {
return {
name: "John",
ref() {
return this;
}
};
};
let user = makeUser();
alert( user.ref().name ); // John