2009-01-21 7 views

Répondre

8

functionName.call() prend une instance d'objet comme premier paramètre. Il fonctionne alors functionName dans le cadre de cette instance d'objet (par exemple "ce" est l'instance spécifiée)

+0

Merci, cela a du sens. – jonhobbs

5

Si vous ne transmettez rien dans call(), ce sera pareil; la fonction sera exécutée avec la même portée que l'appel à call() est fait:

function test() { 
    alert(this); 
} 

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

Mais si vous passez un objet dans call(), cet objet sera utilisé comme la portée:

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

Permettez-moi un exemple:

<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> 

Pour en savoir plus:
http://www.alistapart.com/articles/getoutbindingsituations

Espoir CA aide.

Questions connexes