call() and apply() allow you to indirectly invoke a function as if it were a method of some other object.
call( )和apply( )允许你间接的引用一个函数,犹如他是其他对象的方法一样。
认识1:call() 和 apply() 可以使你间接调用一个函数,利用调用函数中的方法,可以扩充函数赖以生存的作用域;
认识2:call() 和 apply() 中第一个参数的理解。
如下... ...
-------------------
在JavaScript中,函数也是对象。如下apply的例子,callSum2()函数中,return sum.apply(this, [num1, num2]) ; 意思是返回一个结果,这个结果是间接调用sum()函数,并传入参数得到的。
-----------
每个函数都包含两个非继承而来的方法:apply()和call()。这两个函数都是在特定的作用域中调用函数,实际上等于设置函数体内this对象的值。斜体的话意思不好理解,继续往下看
首先。apply()方法接收两个参数:一个是在其中运行函数的作用域,另一个是参数数组。其中,第二个参数可以是Array的实例,也可以是arguments对象。例如:
function sum(num1, num2) {
return num1 + num2;
}
function callSum1(num1, num2) {
return sum.apply(this, arguments); // 传入arguments对象
}
function callSum2(num1, num2) {
return sum.apply(this, [num1, num2]); // 传入数组
}
console.log(callSum1(10, 10)); //20
console.log(callSum2(10, 10)); //20
知识点1:如何理解第一个参数 this。
英文资料中有一句:the first argumetn is the object on which the function is to be invoked;this arugment is the invocation context and becomes the value of this keyword within the body of the function.
下面我们通过call()方法认识这个this。
call方法与apply()方法的作用相同,他们的区别仅在于接收的参数方式不同。对于call()而言,第一个参数this值没有变化,变化的是其余参数都是直接传递给函数(非数组)。
如书上介绍的,传递参数并非apply()和call()真正的用武之地;他们真正强大的地方是扩充函数赖以生存的作用域。如下面的例子:
window.color = 'red';
var o = { color: 'blue'};
function sayColor(){
alert(this.color);
}
sayColor(); // red
sayColor.call(this); // red 全局作用域中调用该方法,所以this指的是window对象。
sayColor.call(window); //red
sayColor.call(o); // blue ,此时this对象指向了o ,结合apply() :在其中运行函数的作用域,意思是此刻的作用域是对象 o 的作用域
----下面是个人的例子:
var a = 10;
var b = 7;
function sum(a, b) {
console.log('The value of a is '+this.a+'\t'+'and the value of b is '+ this.b); //看下面的红色注释文档
return a + b;
}
/**
* 如果是 sum.call(this, a, b); this指的是window,sum方法中 this.a =10 , this.b = 7;
* 如果是 sum.call(o, a, b); this指的是对象 o,sum方法中 this.a = 1 , this.b = 2;
* 如果是 sum.call(new test(), a, b) this 指的是 test()函数的实例对象,其可以访问原型中的属性(共享) a,b sum方法中 this.a = 100 , this.b = 200。
* 可以理解apply() 和 call()方法中,第一个参数是在其中运行函数的作用域;the object on which the function is to be invoked
*/
function multiple(a, b) {
return sum.call(this, a, b); //
}
function test(){}
test.prototype.a = 100;
test.prototype.b = 200;
var o = {
a: 1,
b: 2
};
multiple(10,20); //全局作用域中调用
以上是本人在初学JavaScript中的遇到的难以理解的地方,整理成笔记,加深印象。其中一些术语的表达难免有不当的地方,望批评指正。
在后期的学习过程中,会完善自己的不足的