【问题标题】:Javascript Inheritance ObjectsJavascript 继承对象
【发布时间】:2019-01-30 10:15:14
【问题描述】:

我有这个层次结构:

public abstract class Foo {};
public class A extends Foo {};
public class B extends Foo {};

我想在 javascript 中为这个层次结构建模。所以我尝试了这样的事情:

var Foo = function () {
  this.doSomething = function(input) {
    //do something
  }
};

var A = function() {
  Foo.call(this);

  this.AdoSomething = function(input) {
    this.doSomething();
    //do more things
  }
}

var B = function() {
  Foo.call(this);

  this.BdoSomething = function(input) {
    this.doSomething();
    //do more things
  }
}

我这样设置层次结构:

var tempFoo;
if (type === 'A') {
    A.prototype = Object.create(Foo.prototype);
    tempFoo = new A();
    tempFoo.AdoSomething(data);
} else {
    B.prototype = Object.create(Foo.prototype);
    tempFoo = new B();
    tempFoo.BdoSomething(data);
}

这很好用。但我想知道是否有更好的方法来做到这一点。我希望 javascript 对象看起来像这样:

var Foo = function () {
  this.doSomething = function(input) {
    //do something
  }
};

var A = function() {
  Foo.call(this);

  this.doSomething = function(input) {
    //call Foo's doSomething, super.doSomething()
    //do more things
  }
}

var B = function() {
  Foo.call(this);

  this.doSomething = function(input) {
    //call Foo's doSomething, super.doSomething()
    //do more things
  }
}

但我不能使用 superclass,因为 IE 不支持它。我使用this answer 尝试调用父方法(Foo 的 dosomething),如下所示:

Foo.prototype.doSomething.call(this)

但这没有用。我收到一条错误消息,提示无法读取未定义的属性调用。

在 javascript 中设置层次结构的最佳方法是什么?

【问题讨论】:

  • 您将函数分配给this.doSomething,而不是this.prototype.doSomething

标签: javascript oop object inheritance polymorphism


【解决方案1】:

问题是你没有把doSomething方法放在Foo.prototype里,你直接把它放在每个Foo对象里。您应该将其定义为:

var Foo = function() {
    // Foo constuctor code here
};
Foo.prototype = {
    doSomething: function(input) {
        console.log("doSomething: ", input);
    }
}

您甚至可以在您链接到的问题的定义中看到这一点,在其myMethod 的定义中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    相关资源
    最近更新 更多