【问题标题】:Javascript Inheritance - Calling a function from another prototype [duplicate]Javascript继承-从另一个原型调用函数[重复]
【发布时间】:2012-11-07 13:47:32
【问题描述】:

可能重复:
Crockford’s Prototypal inheritance - Issues with nested objects

我在从原型 A 获取以下代码以执行原型 B 中的函数时遇到问题,想知道是否有任何简单的解决方案:

var Ob = function () {
  test = 'hi';
}

Ob.prototype.A = {
  that : this,
  root : this,
  goB : function () {
    var that = this;

    console.log('hello');
    that.B.wtf();
  }
}

Ob.prototype.B = {
  that : this,
  root : this,
  wtf : function () {
    var that = this;

    console.log(that);
  }
}

test = new Ob;
test.A.goB();

【问题讨论】:

标签: javascript oop inheritance prototype


【解决方案1】:

当您将对象字面量AB 分配给Ob 的原型时,您就是在原型上放置了两个带有一些方法的对象字面量。您没有将方法放在原型上。因此,当您在实例test 的上下文中对这些对象文字执行该方法时,this 并不意味着您认为它的含义。

【讨论】:

  • 正在调用构造函数。没有错误。
【解决方案2】:

您需要在创建对象后连接您的属性:

var Ob = function () {
    var that = this;

    // set the current root to this instance and return the object
    this.getA = function() {
        that.A.currentRoot = that;
        return that.A;
    };

    this.getB = function() {
        that.B.currentRoot = that;
        return that.B;
    };
};

Ob.prototype.A = {
    goB : function () {
        var that = this.currentRoot;

        console.log('hello');
        that.getB().wtf();
    }
};

Ob.prototype.B = {
    wtf : function () {
        var that = this.currentRoot;

        console.log(that, this);
    }
};


test = new Ob;
test.getA().goB();

一个相当肮脏的技巧是在父对象中使用特权方法来扩充子对象并返回它,以便您可以通过属性访问父对象。肮脏的部分是,如果您缓存对象,则不能保证该属性具有正确的值。所以这或多或少是一种方法,尽管你真的不应该这样做。

【讨论】:

  • A.root = B.root = this; 构造函数中没有 AB 变量。如果您的意思是this.A.root = this.B.root = this;,那么每次调用构造函数时都会覆盖该值。
  • 好点。在重新格式化答案之前,我应该再次检查。我会更新答案。
  • 正是我想要的。谢谢托斯滕。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 2016-07-04
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
相关资源
最近更新 更多