Javascript - 错误扩展对象

时间:2016-04-05 15:25:42

标签: javascript

我的代码如下:

function Example(){}
Example.myMethod = function(){};
function SpecificExample(){}
SpecificExample.prototype = Object.create(Example.prototype);
SpecificExample.prototype.constructor = SpecificExample;

我希望SpecificExample延伸Example。为什么这段代码不起作用?

1 个答案:

答案 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.