对象 F 有一个存储为 this.fn
和 this.state.fn
的函数。可以作为 f.fn()
成功调用,但不能作为 f.state.fn()
function F( i, f ) { this.i = i; this.state = { 'fn':f }; this.f = f; }; F.prototype.inc = function() { this.i++ }; F.prototype.fn = function() { this.state.fn() }; f1 = new F( 1, function() { console.log( this.i ); } ); f1.f(); // this works f1.inc(); // this works f1.state.fn; // prints the function f1.fn(); // undefined! f1.state.fn(); // undefined!
问题似乎是该函数存储在对象 state
中,因为它有效:
f1.state.fn.call( f1 ); F.prototype.fn = function() { this.state.fn.call(this); };
这似乎暗示 F.state.fn
中的 this
上下文不是 F
而是F.state
- 这对我来说完全违反直觉 - 这是对的吗!?
最佳答案
在一个函数中,this
完全取决于您调用该函数的方式。
当您使用对象中的点符号调用函数时,this
将自动设置为该对象。
如果你说 someObject.someChildObject.someFunction()
然后在 someFunction()
你会发现 this
将被设置为 someChildObject
.
因此在您的示例中,f1.fn()
应该导致 this
在 fn()
中成为 f1
, 但随后在该函数中你说 this.state.fn()
- 这将调用 state
的 fn()
和 this
设置为 state
。
您可以使用 call
或 apply
覆盖此行为。
另一个例子只是为了你的兴趣:
function F( i, f ) {
this.i = i;
this.state = { 'fn':f };
this.f = f;
};
f1 = new F( 1, function() { console.log( this.i ); } );
f1.f(); // works - 'this' will be f1
var x = f1.f; // create a reference to the same function
x(); // won't work - 'this' will probably be 'window'
如果您创建对最初定义为对象属性的函数的引用,并通过该引用调用该函数,那么 this
将适用于您的新引用。在我的示例中,x
引用是全局的,这实际上意味着它属于 window
对象。您可以从中了解到,f1.f()
调用的函数根本不属于 f1
。
继续那个例子:
f2 = {};
f2.i = "hello";
f2.f = f1.f;
f2.f(); // 'this' will be f2, so should log "hello"
当你调用f2.f()
时,你会发现this
被设置为f2
,因为我设置了一个property f2.i
该函数将记录该属性。
关于javascript - 在 javascript 中, "this"在对象的对象中运行时似乎丢失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6894908/