0

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?

elclanrs
  • 92,861
  • 21
  • 134
  • 171
rlubke
  • 965
  • 5
  • 14
  • 1
    Have you checked here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create? I'm not sure you're using the second parameter to `Object.create` properly... – elclanrs Feb 28 '14 at 00:49
  • Eric has given a good answer, if you need more examples of how to use the prototpe and things that can go wrong because prototype is shared then maybe this answer will help you out: http://stackoverflow.com/a/16063711/1641941 – HMR Feb 28 '14 at 04:26

1 Answers1

2

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
Eric H.
  • 6,894
  • 8
  • 43
  • 62