var c = {
name: 'The c object',
log: function() {
this.name = 'Updated c object';
console.log(this);
var setname = function(newname) {
this.name = newname;
console.log(this);
}
setname('Updated again! The c object');
console.log(this);
}
}
c.log();
第二个console.log为什么是指向window???
this的指向分为四种
1、作为对象的方法调用;
2、作为普通函数调用;
3、构造器调用;
4、Function.prototype.call 或 Function.prototype.apply调用
(1)作为对象的方法调用,此时this指向该对象;
(2)作为普通函数调用,此时指向全局对象window对象
(3)构造器调用
JS没有类,需要构造器来创建对象。除了宿主提供的函数,大部分JS函数都可以当做构造器使用。构造器跟普通函数一模一样,区别在于调用方式。当用new运算符调用函数时,函数会返回一个对象,通常情况下,构造器的this指向返回的这个对象。
(4) call ,apply和bind,this的指向为传入的第一个参数(自定义this指向)