无法弄清楚如何从父对象的回调中访问子对象的“扩展”属性。我的两次尝试如下。我希望函数“say_something”能够提醒“say hi”,其中“hi”来自 child 。相反,它说“说未定义”。
尝试 1:我创建一个对象“a”,然后创建一个派生自它的新对象“b”。但是“a”中的回调(此处来自 setTimeout)将无法访问正确的“this”。
var a = {};
a.say_something = function () { setTimeout( function () { alert( "say " + this.text ); }, 0 ); };
var b = Object.create( a );
b.text = "hi";
b.say_something(); // alerts "say undefined"
尝试 2:常识认为重新安排以允许可以在回调中访问“that”变量。但与“this”不同,“that”无法访问“b”的属性:
var a = ( function () {
var that = {};
that.say_something = function () { setTimeout( function () { alert( "say " + that.text ); }, 0 ); };
return that;
}() );
var b = ( function () {
var that = Object.create( a );
that.text = "hi";
return that;
}() );
b.say_something(); // alerts "say undefined"
PS,我使用 Douglas Crockford 的 Object.create 函数而不是(令我困惑的)new()。复制到这里:
if ( typeof Object.create !== "function" ) {
Object.create = function ( o ) {
function F() {}
F.prototype = o;
return new F();
};
}
最佳答案
如果添加
a.say_something();
对于您的第一个示例,它还将返回 say undefined
。问题是setTimeout
不会在调用它的范围内执行它调用的代码。
我们可以通过以下任一方式解决这个问题:
方法 #2 就是您正在寻找的。p>
var a = {};
a.text = "hello!";
function say_something() {
var that = this; // Save the reference to *this* this.
setTimeout( function() { console.log.call(that, "say " + that.text ); }, 0 );
}
a.say_something = say_something;
a.say_something(); // say hello!
var b = ( function () {
var that = Object.create( a );
that.text = "hi there!";
return that;
}() );
b.say_something(); // say hi there!
关于A 中的 JavaScript : when B inherits from A, 回调看不到 B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4413700/