【问题标题】:How to do prototypal inheritance in this case?在这种情况下如何进行原型继承?
【发布时间】:2012-04-05 19:26:42
【问题描述】:

如何通过这个示例进行继承。

我正在尝试创建一个用作单例的对象字面量。在此我想提取我的课程。除此之外,这些类应该在适用时相互继承。

像这样:

var Singleton = {

    car: function() {
        this.engine= true;
    },

    ford: function() {
        this.color = 'red';
    }
};

我想让 ford 从 bar 继承,但我不能这样做:

    ford: function() {
        this.color = 'red';
        this.prototype = new this.car();
    }

有什么想法吗?

【问题讨论】:

  • 要开始使用,请使用构造函数而不是对象字面量。
  • “bar 继承自 foo”到底是什么意思? foo 和 bar 将用作 new 调用的构造函数吗?
  • 是的。还有@Rob,为什么?
  • @Kriem 构造函数是函数。实例是通过添加前缀new 运算符来创建的,该运算符创建一个从构造函数原型继承方法的对象。

标签: javascript inheritance prototype


【解决方案1】:
var Something = {

    foo: function() {
        this.greet = 'hello';
    },
    bar: function() {
        this.color = 'blue';
    }
};

Something.bar.prototype = new Something.foo();
alert((new Something.bar()).greet)

这是inheritance的入门介绍

【讨论】:

    【解决方案2】:

    如果你试图让bar 继承foo 的属性,那么你可以这样做(注意,这样你不会继承原型属性):

    var Something = {
        foo: function() {
            this.greet = 'hello';
        },
        bar: function() {
            Something.foo.call(this);
            this.color = 'blue';
        }
    };
    

    然后像这样使用它:

    var bar = new Something.bar();
    bar.color // blue
    bar.greet // hello
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      function Foo() {
          this.greet = "hi!";
      }
      
      Bar.prototype = new Foo;
      
      function Bar(color) {
          Foo.apply(this.arguments);
          this.color = color;
      }
      
      var myBar = new Bar("red");
      

      以这种方式创建的Bar 将同时具有greet 和color 属性。此方法保留 Prototype 属性。

      【讨论】:

      • 将Foo.apply(this.arguments); 更改为Foo.apply(this, arguments);。此外,创建原型对象的更好方法是Bar.prototype = Object.create(Foo.prototype);。不过对于这个简单的例子来说并不是很重要。
      猜你喜欢
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-01
      • 2014-05-05
      相关资源
      最近更新 更多