因为 js中 function 是动态绑定zhis
万能公式:谁调用,谁是this,全局中调用,全局对象是this。
var fullname = 'John Doe';
var obj = {
fullname: 'Colin Ihrig',
prop: {
fullname: 'Aurelio De Rosa',
getFullname: function() {
return this.fullname;
}
}
};
var test = obj.prop.getFullname;
console.log(obj.prop.getFullname());
console.log(test());
//打印,谁调用谁的zhis 。 node环境有 fullname 没有挂载到 globa,所以 undefined
Aurelio De Rosa
John Doe
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();
//打印
outer func: this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar
var obj = {
x: 10,
fn: function() {
function f() {
console.log(this);
console.log(this.x);
}
f();
}
};
obj.fn();
//打印
window
undefined
function a(xx) {
this.x = xx;
return this
};
var x = a(5);
var y = a(6);
console.log(x.x);
console.log(y.x);
//打印
undefined
6