Pri*_*ank 6 javascript design-patterns
什么是Javascript中的调用模式参考函数调用模式,我该如何使用它?使用此调用模式有什么好处.
CMS*_*CMS 24
使用apply与函数上下文(this关键字)和参数传递有关.
首先,我认为您应该知道隐式设置this关键字的情况:
1-当函数作为方法调用时(该函数作为对象的成员调用):
obj.method(); // 'this' inside method will refer to obj
Run Code Online (Sandbox Code Playgroud)
2-正常函数调用:
myFunction(); // 'this' inside the function will refer to the Global object
// or
(function () {})();
Run Code Online (Sandbox Code Playgroud)
3-使用new操作员时:
var obj = new MyObj(); // this will refer to a newly created object.
Run Code Online (Sandbox Code Playgroud)
这是时候apply和call来,这些方法让你在调用函数时显式设置上下文,例如:
function test(a) {
alert(this + a);
}
test.call('Hello', ' world!');
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,当test调用函数时,将this关键字设置为String('Hello'),并传递a参数(' world.').
二者,call和apply改变执行功能(的上下文中this所调用的函数内的关键字),但差异在它们之间是与apply,则可以发送一个数组或数组状物体作为要执行的函数的参数,这非常有用,例如:
function sum() {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
var args = [1,2,3];
sum.apply(null, args); // will return 6
Run Code Online (Sandbox Code Playgroud)
这可以避免一些非常hacky,坏(和常见)的eval调用,如:
eval('sum(' + args.join() +')');
Run Code Online (Sandbox Code Playgroud)
另一个例子,Math.max和Math.min方法,这些方法可以接收任意数量的参数,如:
var max = Math.max(2,4,6,8); // 8
Run Code Online (Sandbox Code Playgroud)
但是,如果你有一个数字数组怎么办?
var numbers = [2,4,6,8];
numbers.push(10);
var max = Math.max.apply(null, numbers); // 10
Run Code Online (Sandbox Code Playgroud)
还要注意,当null或undefined用作this参数时,call或者apply,this对象将引用Global对象(类似于情况#2,正常函数调用).
对于Math.max例如,上下文是不是真的有关,因为他们就像是"静态"的方法,该this关键字不是在内部使用...