this
this
- 函数在执行时,JS解释器每次都会传递一个隐含的参数
- 这个参数就叫做this
- this会指向一个对象
- this所指向的对象会根据函数调用方式的不同而不同
- 以函数的形式调用时,this指向的是window
- 以方法的形式调用时,this指向的是调用方法的对象
- this所指向的对象会根据函数调用方式的不同而不同
- 通过this可以在方法中引用调用方法的对象
function fn() {
console.log(this === window);
}
fn(); // true
const obj = { name: "孙悟空" };
obj.test = fn;
obj.test(); // false