在这种情况下如何进行原型继承

How to do prototypal inheritance in this case?

本文关键字:原型 继承 何进行 这种情况下      更新时间:2023-09-26

如何使用此示例进行继承。

我正在尝试创建一个充当单例的对象文字。在此中,我想提取我的类。接下来,这些类应该在适用时相互继承

这样:

var Singleton = {
    car: function() {
        this.engine= true;
    },
    ford: function() {
        this.color = 'red';
    }
};

我想让福特从酒吧继承,但我不能这样做

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

有什么想法吗?

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

这是关于继承的入门

如果你试图让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

你可以做这样的事情:

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属性。此方法保留原型属性。