var myObject = {
func1: function() {
console.log(this); // myObject
var func2 = function() {
console.log(this); // window, 从此处开始,this都是window对象了
var func3 = function() {
console.log(this); // window, head
}();
}();
}
}
myObject.func1();
var foo = {
fun: function(bar) {
console.log(this) // foo
bar(); // window
}
}
foo.fun(function() {console.log(this)})
在ES3中当this值得宿主函数被封装在另一个函数的内部或在另一个函数的上下文中被调用时,this值将永远是对head对象的引用
this在ES5中是固定的
解决this的几个方法
var myObject = {
myProp: 'hah',
myMeth: function() {
var that = this; // myMeth作用域内,保存this引用(也就是myObject)
var helper = function() { // 子函数
console.log(that.myProp); // hah
console.log(this); // window
}();
}
}
myObject.myMeth();
var myObject = {};
var myFunction = function(p1, p2) {
// 调用函数的时候,通过call()将this指向myObject
this.foo = p1;
this.bar = p2;
console.log(this);
};
myFunction.call(myObject, 'foo', 'bar');
console.log(myObject); // Object {foo = 'foo', bar = 'bar'}
var Person = function(x) {
if(x) this.fullName = x;
}
// 原型方法内的this关键字引用构造函数实例
Person.prototype.whatIsMyFullName = function() {
return this.fullName;
}
var cody = new Person('cody lindley');
console.log(cody.whatIsMyFullName()); // cody lindley
Object.prototype.fullName = 'John Doe';
var john = new Person(); // 未传参数
console.log(john.whatIsMyFullName()); // John Doe