Javascript apply与call函数详解

来源:互联网 发布:手机直播完整源码 编辑:程序博客网 时间:2024/05/20 18:05

一、apply

1、apply的作用:委托或者代理一个方法
apply的作用,说白了,其实就是用来调用一个函数,并更改被调用函数的this所指向的对象的。我觉得其实apply就是委托或者代理。这句话看着有点抽象,先看下面例子再回看这句话


2、示例1:无参的和一个参数的apply
apply()的参数为空时,默认调用全局对象

var x = 0;function test(){  alert(this.x);}var Q={};Q.x = 1;Q.m = test;Q.m.apply(); //弹框内容为全局的x的0,而不是Q的x的1

因为Q.m=test所以其实Q.m.apply()这句代码的意思就是,执行test,并使test函数里面的this为全局对象。说白了,Q.m()和Q.m.apply()并没有什么区别,都是执行test,不同的是apply改变了test内的this,使其为全局对象。
若把最后一行改为Q.m.apply(Q);这句代码的意思是Q.m的this为Q,即此时test的this为Q,于是弹框内容为Q的x的1


3、apply本质
结合一跟二来看,在二中的代码的最后一行Q.m.apply();这句代码的本质含义,其实就是apply调用Q.m,也就是test函数,然后apply把test的this改为全局对象window。再说的详细点,或许可以这么说,Q.m把自己委托给了apply,嗯,没错,就是委托。看到这里,基本就可以很好的把握apply了。


4、示例2:两个参数的apply与继承
来个老掉牙的例子吧:

function Person(name,age){      //定义一个人this.name=name;     this.age=age;           this.sayhello=function(){alert("hello")};}function Student(name,age,grade){    //学生类     Person.apply(this,arguments);       //这里实现了继承,后面会有解释this.grade=grade;                               }

然后我们可以:
var s=new Student(“小明”,18,5);
s. sayhello();
我们在定义Student的时候,并没有为Student添加sayhello函数,但是Student却有sayhello函数,这个函数是怎么来的?应当注意到,我们的Student里面有这么一句代码:
Person.apply(this,arguments);由于这句代码是在Student里面的,并且Student是通过new来调用的,所以这句代码里面的this就是Student。所以这句代码的意思,就是执行Person函数,但是Person函数里面的this指向Student,arguments则作为Person的参数。也就是Person.apply(this,arguments);这句代码相当于执行下面这样的代码:

function Person(name,age){      //定义一个人Student.name=name;     Student.age=age;           Student.sayhello=function(){alert("hello")};}

于是Student就有了sayhello函数。


5、apply参数文档
Parameters
thisArg
The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.
argsArray
An array-like object, specifying the arguments with which fun should be called, or null or undefined if no arguments should be provided to the function. Starting with ECMAScript 5 these arguments can be a generic array-like object instead of an array. See below for browser compatibility information.


二、call

call与apply功能相同,用法以及原理也一样,参数略有不同。前面的apply的第二个参数arguments是一个参数数组而call的第一个参数跟apply一样,是一个this,剩下参数都是call调用的参数,call是变参的。示例:

function Product(name, price) {  this.name = name;  this.price = price;}function Food(name, price) {  Product.call(this, name, price);  this.category = 'food';}
0 0
原创粉丝点击