调用具有自己原型的数组中的函数时出错
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
相关文章:
- 尝试调用AngularJS上的函数时出错
- 得到"未定义不是函数“;使用显示原型图案时出错
- 从函数中的函数返回数组时出错
- 从 java 脚本调用函数时 PHP 中出错
- 使用PHP和Javascript在函数内部传递alphaneumeric值作为参数时出错
- 比较$watch函数内的基元类型时出错
- CakePHP错误:在非对象上调用成员函数get(),使用cakejavascript助手时出错
- 构造函数出错
- javascript函数出错
- AngularJS:没有定义$rootscope的全局函数出错,没有定义$scope
- Java脚本函数不;一个函数出错后无法工作
- OnClick函数出错
- 函数b()出错
- for循环中的JavaScript匿名函数出错
- 使用带有href的attr函数出错
- 从外部文件调用JavaScript函数出错
- 使用本地存储的可排序列表函数出错
- 确定数字中位数的函数出错
- PHP邮件函数发送电子邮件,但AJAX函数出错
- ajax函数出错,尽管它转到了我的webservice