我如何在javascript中进行原型继承。通常我这样做 和
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);
代码已给出,请澄清这两种继承方式的区别
当你说
clsChild.prototype = clsParent.prototype;
您正在使
clsChild
和 clsParent
的原型相同。因此,如果您对 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
除了
thefourtheye
所说的。我认为这主要是一个清晰度问题。当每个类都有一个对象来表示它时,考虑对象就更容易了。此外,它可能是实现继承的最常见方式,这也使得它更容易理解。
也没有技术原因不在原型中存储基元值。但是,当您在文件的一部分中定义整数属性,而在另一部分中定义数组属性时,就会变得混乱。
这种方法直接将 clsChild 函数的原型设置为 clsParent 的原型。这意味着 clsChild 对象将与 clsParent 共享完全相同的原型,并且对 clsParent.prototype 的任何更改都将立即影响 clsChild 类型的所有对象。
function clsParent() {
this.myName = "faizan";
this.getMyName = function() {};
}
clsParent.prototype.aProp = "property in prototype";
function clsChild() {
this.Fname = "abr";
}
clsChild.prototype = clsParent.prototype; // No new object created here
var myObj = new clsChild();
console.log(myObj.myName); // "faizan"
console.log(myObj.aProp); // "property in prototype"