问题描述
我正在尝试理解.apply方法。所以,我创建了以下代码:
I am trying to understand the .apply-method. So, I created the following code:
var o = new Object();
o.method = function(x, y) {
return x + y
};
o.method = (function(original) {
return function(x, y) {
var a = 'A';
var b = 'B';
var result = original.apply(this, [a, b]);
return result;
}
})(o.method);
console.log(o.method(1, 2));
我认为最后一个打开和关闭的括号可能为空,因此调用方法o.method自动。但是空括号
I thought that the last open and close parentheses could be empty and so the method o.method is invoked automatically. But with empty parentheses
o.method = (function(original) {
return function(x, y) {
var a = 'A';
var b = 'B';
var result = original.apply(this, [a, b]);
return result;
}
})();
o.method(1, 2);
我收到以下错误:
无法读取属性'apply'of undefined
I get the following error:Cannot read property 'apply' of undefined
有人可以解释一下为什么吗?
Can someone please explain me why?
亲切的问候
Henning
Kind regardsHenning
推荐答案
通过一些更改,您的代码是正确的:
With some change your code is correct:
var o = new Object();
o.method2 = function(x,y){return x+y};
o.method = (function (original){
return function(x,y){
var result = original.call(this, x,y);
return result;
}
})(o.method2);
同样适用于测试和运行:
Also for test and run:
o.method(2,3)
结果为5
还有申请:
var o = new Object();
o.method2 = function(x,y){return x+y};
o.method = (function (original){
return function(x,y){
var result = original.apply(this, [x,y]);
return result;
}
})(o.method2);
然后测试:
o.method(2,3)
结果为5
有关call()和apply()用法的更多信息,请阅读以下文章:
For more information about the usage of call() and apply() you can read this article:http://adripofjavascript.com/blog/drips/invoking-javascript-functions-with-call-and-apply.html
这篇关于无法读取undefined属性'apply'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!