fun.call(thisArg[, arg1[, arg2[, ...]]])
thisArg
在fun函数运行时指定的是this值。在非严格模式下,thisArg为null和undefined的this值会指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象segmentfault
arg1,arg2,……
指定的对象的参数列表数组
在运行的函数中调用另外一个Object的this浏览器
经过 call 方法,你能够在一个对象上继承另外一个对象上的方法app
继承某个对象的方法,对于一些公用的方法能够采起这样的方式Object.apply(this,arguments)
,不必重复声明相同的方法。ide
function People(name, age) { this.name = name; this.age= age; this.sayName=function(){ console.log("my Name is "+name); } } function one(name, age) { People.call(this, name, age); } function two(name, age) { People.call(this, name, age); } var one= new one('Jim', 25); var two= new two('Tom', 40); one.sayName(); //my Name is Jim two.sayName(); //my Name is Tom
function showContent(){ var content="这篇文章的标题是"+this.title+" 做者是"+this.author; console.log(content); } var article={ title:"hello world", author:"coder" } showContent.call(article) //这篇文章的标题是hello world 做者是coder
fun.apply(thisArg, [argsArray])
thisArg
在fun函数运行时指定的是this值。在非严格模式下,thisArg为null和undefined的this值会指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象函数
arg1,arg2,……
一个数组或者类数组对象,可为null和undefinedoop
与call()相似,只是传入参数的方式不一样。this
function getMax(arr){ return Math.max.apply(null,arr) }
与call() 相似prototype
能够看一下hoverdelay.js的源码(这段代码是解决hover事件重复触发的bug),setTimeout会改变this的指向(具体能够看一下这篇文章),可用that=this
,保存以前的this指向,再用apply或者call重定向为原来的this环境。code
(function($){ $.fn.hoverDelay = function(options){ var defaults = { hoverDuring: 200, outDuring: 200, hoverEvent: function(){ $.noop(); }, outEvent: function(){ $.noop(); } }; var sets = $.extend(defaults,options || {}); var hoverTimer, outTimer, that = this; return $(this).each(function(){ $(this).hover(function(){ clearTimeout(outTimer); //使用apply() hoverTimer = setTimeout(function(){sets.hoverEvent.apply(that)}, sets.hoverDuring); },function(){ clearTimeout(hoverTimer); outTimer = setTimeout(function(){sets.outEvent.apply(that)}, sets.outDuring); }); }); } })(jQuery);
Array.prototype.shift.call(arguments)
,arguments是一个类数组对象,虽然有下标,但不是真正的数组,没有shift方法,这时能够经过call或者apply方法调用Array.prototype中的shift方法。
MDN原文:
While the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.
call()和apply()的用法几乎相同,不一样之处在于call()接受的是一个参数列表,而apply()接受的是一个数组参数。(方便记忆的小技巧:Apply for array and Call for comma.)
function showContent(title,author){ var content="这篇文章的标题是"+title+" 做者是"+author; console.log(content); } showContent.apply(undefined, ["hello", "Jim"]); //这篇文章的标题是hello 做者是Jim showContent.call(undefined, "world", "Join"); //这篇文章的标题是world 做者是Join