脚本宝典收集整理的这篇文章主要介绍了javascript代码实例教程-javascript中的apply和call简介,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。小宝典致力于为广大程序猿(媛)提供高品质的代码服务,请大家多多光顾小站,小宝典在此谢过。
在javascript中上下文作用域是一个比较复杂的东西,而apply和call就能让方法的上下文发生改变。
apply的用法:
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:我很不好。
觉得可用,就经常来吧! 脚本宝典 欢迎评论哦! js脚本,巧夺天工,精雕玉琢。小宝典献丑了!
以上是脚本宝典为你收集整理的javascript代码实例教程-javascript中的apply和call简介全部内容,希望文章能够帮你解决javascript代码实例教程-javascript中的apply和call简介所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。