简体   繁体   中英

Object.create and prototype inheritance

This is my first real foray into Javascript. I've read several resources on Object.create() and prototypes, and I thought I was grokking it. However, there's something I'm missing and am hoping the community will be willing to help me out.

Here's my test case

"use strict";

function Ele(name) {
    this.name = name;
}

Ele.prototype = {
    constructor: Ele,
    value: {writable:true}
};

function Application(displayName, description) {
    Ele.call(this, "Application");
    this.displayName.value = displayName;
    this.description.value = description;
}

Application.prototype = Object.create(Ele.prototype, {
    constructor: Application,
    displayName: new Ele("DisplayName"),
    description: new Ele("Description"),
    dataObjectDefs: []
});

var app = new Application("test1", "test2");
var app2 = new Application("test3", "test4");
console.log(app.name);               // Application
console.log(app.displayName.value);  // expected to be test1, but is test4.
console.log(app.description.value);  // expected to be test2, but is test4.
console.log(app2.name);              // Application
console.log(app2.displayName.value); // expected to be test3, but is test4.
console.log(app2.description.value); // expected to be test4, but is test4.

My question is, what am I doing wrong with the Ele instances in the Application definition that is causing the last value set to be the value displayed for both the displayName.value and description.value properties?

What's happening is you are setting the value of the Ele prototype not its instances.

function Ele(name){ this.value = name; } 

function Application(displayName, description) { 
   Ele.call(this, "Application");
   this.displayName = new Ele(displayName); 
   this.description = new Ele (description); 
   this.dataObjectDefs: [] 
 }

 var app = new Application("test1", "test2");
 var app2 = new Application("test3", "test4");
 console.log(app.name);               // Application
 console.log(app.displayName.value);  // tes t1,
 console.log(app.description.value);  //  test2
.

ALso, generally speaking, you want to add methods to an object's prototype, not re-write it. For instance:

Application.prototype.sayMyName = function(){console.log(this.displayName.value)};  
app.sayMyName() // test1

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