function() {
 return this === window // true
}()
$("h1").click(function() {
 $(this).css({"color": "red"}) // "this" becomes DOM element(s) here.
})
对于这样的回调调用,如何JQuery实现this对 from windowto的引用?DOM element
它是使用.apply方法完成的。
https://github.com/jquery/jquery/blob/1.9-stable/src/event.js
thecallback.apply(theelement,theeventobject)
以下是代码的链接:
一切都与范围有关!一般来说,this当前作用域内绑定的对象是由当前函数的调用方式决定的,不能在执行时通过赋值来设置,每次调用函数时都可以不同。
EcmaScript 5 引入了 bind 方法来修复函数,this无论它是如何调用的。
当this关键字出现在函数内部时,其值取决于函数的调用方式。
function() {
   return this === window // true, "this" would be the window
}
function f2(){
    "use strict"; 
    return this;  // "this" would return undefined in  strict mode
}
var o = {
  prop: 'test',
  f: function() {
    return this.prop; // here "this" would be the object o, and this.prop
                      // would equal o.prop
  }
};
var t = o.f(); // t is now 'test'
jQuery 使用call()andapply()来改变this特定范围内的值,这样做是这样的:
function add(c, d){
  return this.a + this.b + c + d;
}
var o = {a:1, b:3};
// The first parameter is the object to use as 'this', 
//subsequent parameters are passed as 
// arguments in the function call
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
// The first parameter is the object to use as 'this', 
// the second is an array whose members are used 
//as the arguments in the function call
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34