call和apply到底有啥用
? ? ?为什么有这两个函数呢?们到底可以做什么?
mozilla官方的文档让我看到了一点端倪:
1、call函数可以让你从已有的对象中继承一个方法,而不必为新对象写一个新的方法
With call, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.2、明确指出函数调用的上下文。
没错,有时候在函数调用的过程中,转来转去常常会让this迷失方向,call和apply函数则可以明确指出此函数调用的this对象是谁。
? ? ? ? 例子如下:
?
var first_object = {num: 42};var second_object = {num: 24};function multiply(mult) {return this.num * mult;}multiply.call(first_object, 5); // 返回 42 * 5multiply.call(second_object, 5); // 返回 24 * 5