文字对象可以从类继承吗?

时间:2017-06-09 18:42:29

标签: javascript oop constructor object-literal

所以我在想一个文字对象是否可以从类继承属性和方法。这是代码

var Foo = function(val1, val2) {
    this.prop1 = val1;
    this.prop2 = val2;
}

var bar = {
    //how to inherit properties from Foo class; also add new property
    prop3: 'val3'
};

3 个答案:

答案 0 :(得分:0)

您的代码中没有继承。继承看起来像这样:

var Foo = function(val1, val2) {}
Foo.prototype={
    prop1:val1,
    prop2:val2
};

var bar = {
//how to inherit properties from Foo class; also add new property
prop3: val3
};

现在你可以这样做:

Object.setPrototypeOf(bar, /*to*/ Foo.prototype);

或创建另一个对象:

var instance=new Foo();
Object.assign(instance,bar);

答案 1 :(得分:0)

您可以通过创建Foo的实例,然后像这样向该实例添加属性来实现此目的:

var Foo = function(val1, val2) {
    this.prop1 = val1;
    this.prop2 = val2;
}

var x = new Foo('valOfProp1', 'valOfProp2');

x.prop3 = 'valOfAddedProp';

答案 2 :(得分:0)

您可以执行以下操作;

var Foo = function(val1, val2) {
    this.prop1 = val1;
    this.prop2 = val2;
};

Foo.prototype.getProp = function(p){
  return this[p]; // NOT!! this.p
};

var bar = {
    //how to inherit properties from Foo class; also add new property
    prop3: "val3"
};

Object.setPrototypeOf(bar,Foo.prototype);
console.log(bar.getProp("prop1"));
console.log(bar.getProp("prop2"));
console.log(bar.getProp("prop3"));