ECMASCript5新特性之Function.prototype.bind

用途:如何在另一个函数中保持this上下文
实例一:

var obj = {
   fun1: function(cb) {
        cb();
   },
   fun2: function() {
     alert(1);
   },
   render: function() {
    var self = this;
        this.fun1(function() {
            self.fun2();
        });
   }
};

用bind方法改进:

var obj = {
   fun1: function(cb) {
        cb();
   },
   fun2: function() {
     alert(1);
   },
   render: function() {
        this.fun1(function() {
            this.fun2();
        }.bind(this)); // 即当前函数的内部的执行对象是this
   }
};

当然,call方法和apply也能实现类似于bind方法的功能,即改变当前函数的执行对象,例如:

var x = 5;
var foo = {
    x: 3
};
var bar = function() {
    console.log(this.x);
}
bar(); // 5
var boundFunc = bar.bind(foo);

boundFunc(); // 3

bar.call(foo); // 3
bar.apply(foo); // 3

猜你喜欢

转载自blog.csdn.net/xujiezi/article/details/51011765
今日推荐