在其自身原型的数组中调用函数时出错(js)

Error when calling function within array of its own prototype (js)

抱歉,如果这是一个愚蠢的问题,我只是在试验,不明白为什么这不起作用:

var MyFunc = function() {};                                                    

MyFunc.prototype = {                                                           
  receive: function() {                                                        
    console.log("Received");                                                   
  },                                                                           
  spine: [MyFunc],                                                             
}                                                                              

var func = new MyFunc();                                                       

func.receive();          //works                                               
func.spine[0].receive(); //error: Object function () {} has no method 'receive'

最后一行是错误行。

完整输出:

Received

/home/zxcv/Documents/CODE/js/stuff/gp/scratch.js:13
func.spine[0].receive(); //error: Object function () {} has no method 'receive
              ^
TypeError: Object function () {} has no method 'receive'
    at Object.<anonymous> (/home/USER/Documents/CODE/js/stuff/gp/scratch.js:13:15)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:929:3

shell returned 8

因为spine[0]是MyFunc(构造函数对象),不是MyFunc的实例对象。 prototype 中定义的函数放在构造函数创建的实例上,而不是构造函数本身。

为了执行函数,您可能需要检查原型

func.spine[0].prototype.receive();

如果您想创建一个可以直接从 MyFunc 执行的方法,您需要在 MyFunc 上实际定义它

MyFunc.receive2 = function(){
    console.log("Received");
};
var func = new MyFunc();
func.spine[0].receive2();
//Or
MyFunc.receive2();

//Note you would not be able to call this directly from the instance
func.receive2(); //would cause an error