简体   繁体   English

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

[英]can a literal object inherit from class?

So I was thinking if a literal object can inherit properties and methods from a class. 所以我在考虑文字对象是否可以从类继承属性和方法。 Here is the code 这是代码

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'
};

Theres no inheritance in your code. 您的代码中没有继承。 Inheritance would look like this: 继承看起来像这样:

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
};

And now you could do: 现在您可以:

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

or creating another object: 或创建另一个对象:

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

You could achieve this by creating an instance of Foo and then adding properties to that instance like so: 您可以通过创建Foo实例,然后向该实例添加属性来实现此目的,如下所示:

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

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

x.prop3 = 'valOfAddedProp';

You may do as follows; 您可以执行以下操作;

 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")); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM