差异b \ w clsParent.prototype和object.create(clsParent.prototype)

时间:2014-03-08 14:52:39

标签: javascript inheritance

我怎样才能在javasciript中进行原型继承。通常我这样做 和

 derivedFn.prototype = object.create(clsParent.prototype)

但是今天我得到了我们也可以这样做,结果是一样的,那么差异是什么

derivedFn.prototype = clsParent.prototype

例如

function clsParent() {
    this.myName = "faizan"
    this.getMyName = function() {}
}
clsParent.prototype.aProp = "property in prototype"

function clsChild() {
    this.Fname = "abr"
}

clsChild.prototype = clsParent.prototype; //what is the difference
//Object.create(clsParent.prototype); 
// what is the difference if i do inheritance by this
var myObj = new clsChild();
console.log(myObj.myName);
console.log(myObj.aProp);

代码请给我说明这两种方式继承的区别

2 个答案:

答案 0 :(得分:3)

当你说

clsChild.prototype = clsParent.prototype;

您正在使clsChildclsParent的原型相同。因此,如果您对clsChild.prototype进行了更改,则更改也会在使用new clsParent()创建的任何对象中显示。

尝试,

clsChild.prototype.a = 1000;
console.log(new clsParent().a);
// 1000

但是当你Object.create(clsParent.prototype)时,它会创建一个从clsParent.prototype延伸的全新对象。因此,对clsChild.prototype进行更改不会影响clsParent.prototype

<强>建议:

在原型中存储属性通常是个坏主意,因为它将由所有实例共享。只有在您的用例要求时才应该这样做。

clsParent.prototype.aProp = "property in prototype"; // Don't do this

答案 1 :(得分:0)

除了thefourtheye所说的。我认为这主要是一个明确的问题。当每个类都有一个对象来表示它时,更容易思考对象。此外,它可能是实现继承的最常用方式,这也使其更容易理解。

此外,没有技术原因不在原型中存储基元值。但是,如果在文件的一个部分中定义整数属性,而在另一个部分中定义数组属性,则会变得混乱。