kjo*_*kjo 1 javascript oop inheritance
在定义了一些构造函数之后,例如Child,我看到了以下两种形式:
Child.prototype = Parent.prototype;
Run Code Online (Sandbox Code Playgroud)
要么
Child.prototype = new Parent();
Run Code Online (Sandbox Code Playgroud)
两个都正确吗?如果是这样,是否有理由偏爱另一个?
虽然@elclanrs的评论是正确的,但是现在您可能更喜欢Object.create,并选择在旧环境中使用它来填充它,对您的问题有一个明确的正确答案.
Child.prototype = new Parent();
Run Code Online (Sandbox Code Playgroud)
远远优于
Child.prototype = Parent.prototype;
Run Code Online (Sandbox Code Playgroud)
原因很简单,在后者中,您添加到子原型的任何属性也包含在父级中.什么时候
Dog.prototype = Animal.prototype;
dog.prototype.bark = function() {console.log("woof, woof");}
Cat.prototype = Animal.prototype;
var frisky = new Cat();
frisky.bark(); //=> woof, woof!
Run Code Online (Sandbox Code Playgroud)
你有猫和狗住在一起......大规模歇斯底里.