javascript中functionName()和functionName.call()之间的区别

时间:2009-01-21 17:06:01

标签: javascript

希望标题是自解释的,与仅编写functionName()相比,在Javascript中使用.call()方法的优点是什么? ?

3 个答案:

答案 0 :(得分:8)

functionName.call()将对象实例作为其第一个参数。然后它在该对象实例的上下文中运行functionName(即“this”是指定的实例)

答案 1 :(得分:5)

如果你没有将任何内容传递给call(),它将是相同的;该函数将以与call()的调用相同的范围运行:

function test() {
    alert(this);
}

test(); // alerts the window object
test.call(); // alerts the window object

但是如果将对象传递给call(),则该对象将用作范围:

test.call("hi"); // alerts "hi"

答案 2 :(得分:1)

让我举个例子:

<html>
<head>
<script type="text/javascript">
 var developerName = "window";
function test(){
   var developer = function(developerName ){ this.developerName  = developerName;}
    developer.prototype = {
      displayName : function(){alert(this.developerName );}
    }
    var developerA = new developer("developerA");
    var developerB = new developer("developerB");
    developerA.displayName();//will display an alert box with "developerA" as its inner text
    developerA.displayName.call();//will display an alert box with "window" as its inner text, in this case the context is the window object.
    developerA.displayName.call(developerB);//will display an alert box with "developerB" as its inner text
}
</script>
</head>
<body>
<input type="button" onclick="test()" value="display names"/>
<body>
</html>

进一步阅读:
http://www.alistapart.com/articles/getoutbindingsituations

希望这有帮助。