Object.create和原型继承

时间:2014-02-28 00:43:47

标签: javascript

这是我第一次真正涉足Javascript。我已经阅读了几个关于Object.create()和原型的资源,我想到我正在研究它。但是,有些东西我不知道,我希望社区愿意帮助我。

这是我的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.

我的问题是,我在应用程序定义中的Ele实例是做错了什么导致最后一个值设置为displayName.value和description.value属性显示的值?

1 个答案:

答案 0 :(得分:2)

您正在设置Ele原型的值而不是其实例。

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
.

另外,一般来说,您希望将方法添加到对象的原型中,而不是重写它。例如:

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