1、纯函数中调用
普通函数直接调用,this指向window对象
function foo() {
var x = 1;
console.log(this, this.x);
}
foo(); //window, 1
2、作为对象方法调用,this指向上级对象
var foo = function(){
console.log(this, this.x);
}
var o = {
x: 1,
m: foo
}
o.m(); //o, 1
3、作为构造函数调用
所谓构造函数,就是通过这个函数生成一个新对象,this就指向这个新对象
function foo(){
this.x = 1;
console.log(this); //foo()
}
var o = new foo();
4、call(), apply()调用
var o = {
x: 1
}
function foo() {
console.log(this);
}
foo.call(o); //o
foo.apply(o); //o
注:call(), apply()的参数为空时,默认调用全局对象
5、Object.prototype.bind
- bind为函数指定新的this对象,并且不能通过call(), 或apply()更改其this对象
- 当再次使用new时,就会自动把this绑定到新对象上, 回覆盖之前的bind
function returnThis () {
console.log(this);
return this;
}
var a = { name: 'aaa'};
var boss1returnThis = returnThis.bind(a);
boss1returnThis(); // a
var b = { name: 'bbb' };
boss1returnThis.call(b); // still a
new returnThis(); //returnThis()