【发布时间】:2014-05-14 08:55:47
【问题描述】:
首先我知道了 apply() 和 call() 的区别。
function theFunction(name, profession) {
alert("My name is " + name + " and I am a " + profession + ".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]); // This call be called theFunction("Susan", "school teacher");, why use apply
theFunction.call(undefined, "Claude", "mathematician"); // This call be called theFunction("Claude", "mathematician");, why use call
从上面的代码中,所有 3 个函数调用都会显示警报消息。
-
与普通函数调用相比,使用apply和call有什么优点/缺点,什么时候使用apply/call合适,请澄清一下。
-
还有一件事,如果函数是基于原型的函数怎么办:
Function.prototype.theFunction = 函数(姓名,职业){
alert("My name is " + name + " and I am a " + profession + "."); }
那么如何使用 apply 或 call 来调用这个函数。我试过这样:
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
但导致错误。 "ReferenceError: theFunction is not defined"
【问题讨论】:
标签: javascript prototype-programming