指点成金-最美分享吧

登录

js 之 call apply

佚名 举报

篇首语:本文由小编为大家整理,主要介绍了js 之 call apply相关的知识,希望对你有一定的参考价值。

在学习js过程中怎么也绕不过用到call、apply方法,感觉都差不多,现在看看他们的用法,区别

在 javascript 中,call 和 apply 都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部 this 的指向。

e.g.

function fruits() {}fruits.prototype = {    color: "red",    say: function() {        console.log("My color is " + this.color);    }}var apple = new fruits;apple.say();    //My color is redbanana = {    color: "yellow"}apple.say.call(banana);     //My color is yellowapple.say.apply(banana);    //My color is yellow

 

 banana本身没有say方法,但是通过这种方式可以say方法,运行时的上下文不是apple了,也是banana,所以显示的是 My color is yellow

apply、call 的区别

对于 apply、call 二者而言,作用完全一样,只是接受参数的方式不太一样。

。例如,有一个函数定义如下:

var func = function(arg1, arg2) {

     

};

  就可以通过如下方式来调用:

func.call(this, arg1, arg2);

func.apply(this, [arg1, arg2])

  其中 this 是你想指定的上下文,他可以是任何一个 javascript 对象(JavaScript 中一切皆对象),call 需要把参数按顺序传递进去,而 apply 则是把参数放在数组里。

  JavaScript 中,某个函数的参数数量是不固定的,因此要说适用条件的话,当你的参数是明确知道数量时用 call 。

  而不确定的时候用 apply,然后把参数 push 进数组传递进去。当参数数量不确定时,函数内部也可以通过 arguments 这个数组来遍历所有的参数。

bind 用法简单示例

// 正常情况下使用变量保存 this 值var foo = {    bar : 1,    eventBind: function(){        var _this = this ;        $(".someClass").on("click",function(event) {            /* Act on the event */            console.log(_this.bar);     //1        });    }}// 使用 bind 进行函数绑定var foo = {    bar : 1,    eventBind: function(){        $(".someClass").on("click",function(event) {            /* Act on the event */            console.log(this.bar);      //1        }.bind(this));    }}

 

在上述代码里,bind() 创建了一个函数,当这个click事件绑定在被调用的时候,它的 this 关键词会被设置成被传入的值(这里指调用bind()时传入的参数)。因此,这里我们传入想要的上下文 this(其实就是 foo ),到 bind() 函数中。然后,当回调函数被执行的时候, this 便指向 foo 对象

apply、call、bind比较

var obj = {    x: 81,};var foo = {    getX: function() {        return this.x;    }}console.log(foo.getX.bind(obj)());      //81console.log(foo.getX.call(obj));        //81console.log(foo.getX.apply(obj));       //81

 

三个输出的都是81,但是注意看使用 bind() 方法的,他后面多了对括号。

  也就是说,区别是,当你希望改变上下文环境之后并非立即执行,而是回调执行的时候,使用 bind() 方法。而 apply/call 则会立即执行函数。

  再总结一下:

  • apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
  • apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文;
  • apply 、 call 、bind 三者都可以利用后续参数传参;
  • bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用 。

参考:http://www.admin10000.com/document/6711.html

以上是关于js 之 call apply的主要内容,如果未能解决你的问题,请参考以下文章