1 对象中方法 函数中的this 指的是包含它的对象, 子对象中的this指的是全局在浏览器中是 window 对象
var obj1 = {this1funcA: function() {var obj2 = {innerFunc: function() {this2}};obj3={ this3 }}obj4={ this4 }
};
在这个对象中,this 的指向会随着调用上下文的变化而变化。在 obj1.funcA() 方法中,this 指向 obj1 对象。而在 obj2.innerFunc() 方法中,this 指向 obj2 对象。 obj3 没有定义在任何函数或方法体内,因此 obj3 被认为是全局变量,它的 this 指向全局对象(在浏览器中是 window 对象)。 同理,obj4 等同于 obj3,它也被认为是全局变量,因此 this 指向全局对象。
2
var obj1 = {this1: "obj1",funcA: function() {console.log("funcA this:", this); // obj1var obj2 = {innerFunc: function() {console.log("innerFunc this:", this); // obj2}};obj2.innerFunc();},obj4: {this4: "obj4",innerObj: {innerFunc: function() {console.log("innerFunc this:", this); // innerObj}}}
};obj1.funcA();
obj1.obj4.innerObj.innerFunc();
funcA this: {this1: "obj1", funcA: ƒ, obj4: {…}}
innerFunc this: {innerFunc: ƒ}可以看到,funcA 中的 this 指向 obj1,innerFunc 中的 this 指向 obj2。