关于Function原型中的bind方法处理this问题

在认识此方法之前,对于防止this的丢失问题,都是采用一个变量去储存然后在其他的作用域(特别是this改变的域中)中去调用这个变量继续使用之前的this。如:var This = this;

当知道Function原型中的bind方法可用来处理关于this的问题之后,我渐渐的喜欢上了采用此方法去处理this的改变问题。好处是使用方便,代码简约。

当然此方法在非标准浏览器下是不存在的,例如IE8及其以下版本的浏览器,其处理办法是添加代码去预判Function的原型中是否存在bind方法,如果不存在则需要我们自己去定义代码,如下:

//对IE不支持Function.bind的处理
    if (!Function.prototype.bind) { 
        Function.prototype.bind = function (oThis) { 
            if (typeof this !== "function") { 
                // closest thing possible to the ECMAScript 5 internal IsCallable function 
                throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); 
            } 
            var aArgs = Array.prototype.slice.call(arguments, 1), 
                fToBind = this, 
                fNOP = function () {}, 
                fBound = function () { 
                    return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); 
                }; 
            fNOP.prototype = this.prototype; 
            fBound.prototype = new fNOP(); 
            return fBound; 
        }; 
    };

以上配置好支持环境之后就可以放心的去使用bind方法了,看如下关于此方法的运用

var name = '王二',
        age = 30,
        json = { 'name': '张三', 'age': 25 };
    
    function printFn(str) {
        alert( '姓名:'+ this.name +',年龄:'+ this.age );
    };
    printFn.bind(json)();
    
    //匿名函数自执行调用bind的方法
    ;(function(){
        alert( '姓名:'+ this.name +',年龄:'+ this.age );
    }.bind(json))();

接下来我们采用bind方法去实现var This = this; 同样的效果,看代码

var json = {
        'index': 5,
        'testFn': function(){
            alert( this.index );//结果是5
            
            ;(function(){
                //当this的指向被改变之后,此this非上面的this
                alert( this.index );//所以此结果是undefined
            })();
            
            //为了获取到真正的this而又不想用var This = this;这种变量去存储this的写法,于是我们可以采用FUNCTION原型中的bind方法来处理this指向问题
            ;(function(){
                //此时的this就是上面的了,也就是 变量json
                alert( this.index );//所以此结果是5
            }.bind(this))();
        }
    };
    json.testFn();

注:用了bind之后,其function作用域内的this都会指向你所绑定的那个对象

posted @ 2015-03-09 16:58  jerry2359  阅读(399)  评论(0)    收藏  举报