日期:2014-05-16  浏览次数:20441 次

谁能给我详细解释一下 javaScript 中的 call
call()   看了文档不理解:调用一个对象的一个方法,以另一个对象替换当前对象。
什么意思啊

------解决方案--------------------
http://bbs.51js.com/viewthread.php?tid=67013&highlight=call
------解决方案--------------------
比如
<script language=javascript>
function test()
{
alert( "haha ")
}
test.call(null,null)
//就相当于test()
</script>
第一个参数是对象,第二个以后的是参数
比如
abc.call(gg,a,b,c)
就相等于
gg.abc(a,b,c)
------解决方案--------------------
http://bbs.51js.com/viewthread.php?tid=59672&highlight=call


------解决方案--------------------
Calls a method of an object, substituting another object for the current object.

call([thisObj[, arg1[, arg2[, [, argN]]]]])

Arguments
thisObj
Optional. The object to be used as the current object.

arg1, arg2, , argN
Optional. List of arguments to be passed to the method.

Remarks
The call method is used to call a method on behalf of another object. The call method allows you to change the object context of a function from the original context to the new object specified by thisObj.

If thisObj is not supplied, the global object is used as thisObj.

------解决方案--------------------
<script language= "JavaScript ">
<!--
function add(a,b)
{
return a+b;
}
function sub(a,b)
{
return a-b;
}
var x=sub.call(add,3,1);//相当于sub(add.arguments[0],add.arguments[1]);即用sub方法代替了当前的add方法,并把add方法中的实参赋sub方法的形参。
alert( "sub.call(add,3,1)= "+x);
//-->
</script>
------解决方案--------------------
<script language= "JavaScript ">
<!--
function add(a,b)
{
return a+b;
}
function sub(a,b)
{
return a-b;
}
var x=sub.call(add,3,1);//相当于sub(add.arguments[0],add.arguments[1]);即用sub方法代替了当前的add方法,并把add方法中的实参赋sub方法的形参。
alert( "sub.call(add,3,1)= "+x);
//-->
</script>


var x=sub.call(add,3,1);
输出2

就相当于var x=sub(3,1);//

------解决方案--------------------
用到时自然就明白了!

俺曾在 XTree 里看到 call 的使用,主要在原型继承的类之间使用!

挺有意思的,有时间再去研究一下!