324*_*423 25 javascript scope function
我试图理解为什么在javascript中,您可能想要更改函数的上下文.我正在寻找一个真实世界的例子或某些东西,它将帮助我理解这项技术的使用方式/原因以及它的意义.
使用此示例说明了该技术(来自http://ejohn.org/apps/learn/#25)
var object = {};
function fn(){
return this;
}
assert( fn() == this, "The context is the global object." );
assert( fn.call(object) == object, "The context is changed to a specific object." );
Run Code Online (Sandbox Code Playgroud)
Gre*_*reg 20
jQuery利用它来达到很好的效果:
$('a').each(function() {
// "this" is an a element - very useful
});
Run Code Online (Sandbox Code Playgroud)
实际的jQuery代码如下所示:
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
Run Code Online (Sandbox Code Playgroud)
如果只是这样做,callback( name, object[ name ] )那么this就不会将你的迭代器设置为当前对象,而是必须使用参数.基本上它只是让事情变得更容易.
请看一下这个例子:
<script>
var el = document.getElementById('button');
el.onclick = function(){
this.value = "Press Me Again"; //this --> now refers to the the element button not on the window
}
//Another Example:
var Person = function(name,location){
this.name = name;
this.location = location;
alert(this.location);
}
var p2 = new Person("Samantha","California"); //this refers to the instance of the function Person(Person now acts as a class)
var p1 = Person(); // this refers to the window(Person simply acts as a simple function)
</script>
<button id="button1">Press Me</button>
Run Code Online (Sandbox Code Playgroud)
新关键字会更改上下文.