1. 全局环境下的this
在全局环境中(在浏览器中是window对象,在Node.js中是global对象),this指向全局对象。
console.log(this === window); // 在浏览器中为true
console.log(this.document !== undefined); // true,因为this指向window,window有document属性
2. 函数调用中的this
在普通函数调用中(即非方法调用),this指向全局对象(在严格模式下this是undefined)。
function test() { console.log(this === window); // 在非严格模式下为true
} test(); function strictTest() { "use strict"; console.log(this === undefined); // 在严格模式下为true
} strictTest();
3. 方法调用中的this
当一个函数被赋值给对象的一个属性,并作为该对象的方法被调用时,this指向该对象。
var obj = { prop: 'value', method: function() { console.log(this.prop); // 'value',因为this指向obj }
}; obj.method();
4. 构造函数中的this
在使用new关键字调用构造函数时,this指向新创建的对象实例。
function MyConstructor() { this.prop = 'value';
} var myObject = new MyConstructor();
console.log(myObject.prop); // 'value',因为this在MyConstructor中指向了myObject
5. 使用call、apply和bind方法
call和apply方法可以显式地设置this的值。
-
apply()把参数打包成Array再传入; -
call()把参数按顺序传入。
比如调用Math.max(3, 5, 4),分别用apply()和call()实现如下:
Math.max.apply(null, [3, 5, 4]); // 5
Math.max.call(null, 3, 5, 4); // 5
bind方法返回一个新函数,这个新函数在被调用时,其this被永久绑定为bind的第一个参数。
function greet() { return "Hello, " + this.name;
} var obj = {name: "World"}; console.log(greet.call(obj)); // Hello, World
console.log(greet.apply(obj)); // Hello, World var boundGreet = greet.bind(obj);
console.log(boundGreet()); // Hello, World
6. 箭头函数中的 this
箭头函数不绑定自己的this,它会捕获其所在上下文的this值,作为自己的this值。
var obj = { prop: 'value', method: function() { return () => this.prop; // 箭头函数中的this指向obj }
}; console.log(obj.method()()); // 'value'