js的this作用域问题

js的this的作用域一直是很头疼的问题,稍有不慎就会undefined或出错.

<input type="button" value="百度一下" id="bt"/>
<SCRIPT LANGUAGE="JavaScript">
<!--

/*
// The .bind method from Prototype.js
Function.prototype.bind = function(){
    var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();
    return function(){
        return fn.apply(object,
        args.concat(Array.prototype.slice.call(arguments)));
    };
};
*/

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

var obj = {
    name: 'A nice demo',
    fx: function() {
    alert(this.name);
    }
};

window.name = 'I am such a beautiful window!';
function runFx(f) { f(); }

//runFx(obj.fx); //弹出 “I am such a beautiful window!”
//runFx(obj.fx.bind(obj)); //弹出 “A nice demo”

    var myObj = {
        value:"这是myObj对象中的value值",
        fun1:function(){
            var obj = document.getElementById("bt");
            var self = this;
            //obj.onclick= this.fun2; //弹出 “百度一下”
            //obj.onclick = function(){ self.fun2.call(obj); } //弹出 “百度一下”
            obj.onclick = function(){ self.fun2.call(self); } //弹出 “这是myObj对象中的value值”
            //obj.onclick = function(){ runFx(self.fun2.bind(self)); } //弹出 “这是myObj对象中的value值”
        },
        fun2:function(){
            alert(this.value);
        }
    }
    myObj.fun1();
//-->
</SCRIPT>

 

 

posted @ 2012-05-18 12:01  php学习笔记  阅读(223)  评论(0编辑  收藏  举报