总结JavaScript中的this

1.理解
      this为晚绑定. 确定的值为最终调用时所依附的对象, 即xxx.yyy()语法. 没有指定则为全局对象, 网页中为window对象.
      赋值语句仅复制函数对象的引用. 函数定义时的绑定信息将被丢弃.
2.实际
      由于this于运行时会被改写,一个常见的技巧是用var o_this = this, 然后通过闭包传递.
      可以通过Funtion的apply方法手工绑定this, 模拟C#中委托中的行为.

var g_prefix = "I'm a ", g_postfix = ".";
var g_says = function(prefix, postfix) {
    alert(prefix 
+ this.msg + postfix);
}

window.msg 
= "windoW";

var man = {    msg: "maN",    says: g_says, hisCat: { msg: "caT", says: g_says } }

g_says(g_prefix, g_postfix); 
// I'm a windoW.
man.says(g_prefix, g_postfix); // I'm a maN.
man.hisCat.says(g_prefix, g_postfix); // I'm a caT.
man.simulateCatSayingButFail = man.hisCat.says; // Want to simulate cats saying..
man.simulateCatSayingButFail(g_prefix, g_postfix); // ..but fails. The man is saying "I'm a maN."

// Really want to simulate cat saying?

Function.prototype.bind 
= function(obj) {
    
var o_this = this;
    
return function() {
        
return o_this.apply(obj, arguments);
    };
}

man.simulateCatSaying 
= man.hisCat.says.bind(man.hisCat); // Want to simulate cats saying..
man.simulateCatSaying(g_prefix, g_postfix); // ..Now saying "I'm a caT."

 

posted @ 2009-09-16 21:21  FlyingCat  阅读(432)  评论(0)    收藏  举报