我的代码如下:
function Example(){}
Example.myMethod = function(){};
function SpecificExample(){}
SpecificExample.prototype = Object.create(Example.prototype);
SpecificExample.prototype.constructor = SpecificExample;
我希望SpecificExample
延伸Example
。为什么这段代码不起作用?
答案 0 :(得分:2)
Example.myMethod是附加到构造函数/对象的函数,但它不是其原型的一部分。这可以称为静态函数(在ES6中就是这样)。要使它们成为原型的一部分,请将它们添加到原型中:
function Example(){}
Example.prototype.myMethod = function(){};
function SpecificExample(){}
SpecificExample.prototype = Object.create(Example.prototype);
// As @JaredSmith said, you shouldn't change the constructor, and why would you?
// function SpecificExample(){} IS your constructor. So...
// SpecificExample.prototype.constructor = SpecificExample;
// should simply be removed.