javascript - 在 javascript 中, "this"在对象的对象中运行时似乎丢失了

标签 javascript object scope this

对象 F 有一个存储为 this.fnthis.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() 应该导致 thisfn() 中成为 f1 , 但随后在该函数中你说 this.state.fn() - 这将调用 statefn() this 设置为 state

您可以使用 callapply 覆盖此行为。

另一个例子只是为了你的兴趣:

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/

相关文章:

javascript - OpenSocial 是可行的 API 选择吗?

javascript - IE9 本地文件系统安全性阻止 js 执行

javascript - Jquery 对话框不提交表单

c++ - 使用 std::array 与数组传递对象数组

scala - 在 DSL 中隐藏和限定隐式变量的创建

ruby-on-rails - 如何重写类范围内声明的方法?

javascript - JavaScript 对象的 ClojureScript 深度相等

python - 创建具有默认值 Python 属性的对象

javascript - 为什么 for..in 循环不遍历对象的原型(prototype)

scope - 访问 WebComponent 内的顶级函数