我的代码如下:
function Example(){}
Example.myMethod = function(){};
function SpecificExample(){}
SpecificExample.prototype = Object.create(Example.prototype);
SpecificExample.prototype.constructor = SpecificExample;
我想要 SpecificExample
扩展 Example
。为什么这段代码不起作用?
最佳答案
Example.myMethod 是附加到构造函数/对象的函数,但它不是其原型(prototype)的一部分。这可以称为静态函数(在 ES6 中就是这样)。要使它们成为原型(prototype)的一部分,请将它们添加到原型(prototype)本身:
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.
关于Javascript - 扩展对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36430646/