javascript中的apply和call简介

在javascript中上下文作用域是一个比较复杂的东西,而apply和call就能让方法的上下文发生改变。

apply的用法:

function.apply(thisobj,args)

thisobj:调用function方法的作用域,在function方法中this表示

args:function的参数,是一个数组,数组中的每个元素代表function的一个参数。

先看一下下面的代码:

        var Dog = function(name){
            this.name = name;
        }

        Dog.prototype.say=function(word){
            alert(this.name+":"+word);
        }

        var dog1 = new Dog("dog1");
        var dog2 = new Dog("dog2");
        dog1.say("你好啊。");   //dog1:你好啊。
        dog1.say.apply(dog2,["我很不好。"]); //dog2:我很不好。

通过 dog2.say.apply(dog2,["我很不好。"]),可以把say方法中的this作用域变成dog2。

当在setTimeout和setInterval中apply这种改变this作用域的方式就有用处了

就上面的代码改造:让调用say的时候过200毫秒后执行alert(this.name+":"+word);

如果代码改写成:

        var Dog = function(name){
            this.name = name;
        }

        Dog.prototype.say=function(word){
            setTimeout(function(){
                alert(this.name+":"+word);
            },200);

        }

        var dog1 = new Dog("dog1");
        var dog2 = new Dog("dog2");

        dog1.say("你好啊。");   //:你好啊。

这样的话this.name就变成空了,因为this的作用域变成了Window对象了。

所以可以用apply的方法把this作用域换回dog1,如下:

        var Dog = function(name){
            this.name = name;
        }

        Dog.prototype.say=function(word){
            setTimeout(function(word){alert(this.name+":"+word);}.call(this,word)
                ,200);
        }
        dog1.say("你好啊。");   //dog1:你好啊。

这样就能实现该功能了。

当然最好的方式还是使用javascript的闭包。

上面的apply完全可以用call来重写。

call用法:

function.call(thisobj,arg1,arg2,...)

thisobj:调用function方法的作用域,在function方法中this表示

arg1,arg2,...:function的参数(与apply不同的是,call是一个一个写出来,而apply则是数组)

用call改造:

        var Dog = function(name){
            this.name = name;
        }

        Dog.prototype.say=function(word){
            setTimeout(function(word){alert(this.name+":"+word);}.call(this,word)
                ,200);
        }

        var dog1 = new Dog("dog1");
        var dog2 = new Dog("dog2");

        dog1.say("你好啊。");   //dog1:你好啊。
        dog1.say.call(dog2,"我很不好。"); //dog2:我很不好。

 

 

 

posted @ 2013-04-23 19:42  小虾Joe  阅读(1490)  评论(4编辑  收藏  举报