A 中的 JavaScript : when B inherits from A, 回调看不到 B

标签 javascript callback scope this

无法弄清楚如何从父对象的回调中访问子对象的“扩展”属性。我的两次尝试如下。我希望函数“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不会在调用它的范围内执行它调用的代码。

我们可以通过以下任一方式解决这个问题:

  1. 对现有对象的引用进行硬编码 alert('say ' + a.text);
  2. 使用 call() apply() 指定函数应执行的上下文。 (对于最新平台, bind() 也是如此。)

方法 #2 就是您正在寻找的。

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/

相关文章:

javascript - 谷歌地图 API v3.30 : Using forEach on a declared data layer

javascript - 这个 jQuery 示例有什么问题?

javascript - 未捕获的类型错误 : Cannot read property 'innerHTML' of null when unchecking checkbox

javascript - 在同一函数作用域的不同版本上具有闭包的函数

java - Android 从 Activity 到 Fragment 的回调

scope - 没有openid的谷歌登录auth2自定义范围

PHP/CodeIgniter - 在 __construct() 中设置变量,但它们不能从其他函数访问

javascript - javascript 字符串变量有类似 getElementsByTagName() 的函数吗?

javascript - 回调没有效果,函数在回调之前仍然执行

JavaScript OOPS 问题