调用具有自己原型的数组中的函数时出错

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

本文关键字:函数 出错 数组 调用 自己 原型      更新时间:2023-09-26

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

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