简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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