- 在全局代码中使用 this ,指代全局对象(window)。
很少在全局代码中使用 this
- 在函数中使用 this ,它的指向完全取决于函数是如何被调用的,而不是声明时决定的。
function Person(name, age){
this.name = name;
this.age = age;
console.log(this);
}
//通过 new 调用
new Person('张三', 18); //Person {name: '张三', age: 18}
//直接调用
Person('张三', 18); //Window{...}
//通过对象调用
let obj = {
a: 1,
b: 2,
print() {
console.log(this);
}
}
obj.print(); //{a: 1, b: 2, print: ƒ}
//call
function callObj(c,d) {
console.log(this, c, d);
}
callObj.call(obj, 3, 4); //{a: 1, b: 2, print: ƒ} 3 4
//apply
function applyObj(c,d) {
console.log(this, c, d);
}
applyObj.apply(obj, [3, 4]); //{a: 1, b: 2, print: ƒ} 3 4