标签:
bind()方法:
a. ECMAScript5还定义了一个方法:bind()。这个方法会创建一个函数的实例,其this值会被绑定到传给bind()函数的值。
b. 支持bind()方法的浏览器有IE9+、Firefox4+、Safari5.1+、Opera12+和Chrome。
window.color="red"; var o={color:"blue"}; //全局函数定义 function sayColor(){ console.log(this.color); } //bind()方法会创建一个函数的实例,其this值会被绑定到传给bind()函数的值 var objectSayColor=sayColor.bind(o); objectSayColor(); //blue var myObj = { specialFunction: function () { }, anotherSpecialFunction: function () { }, getAsyncData: function (cb) { cb(); }, render: function () { var that = this; this.getAsyncData(function () { that.specialFunction(); that.anotherSpecialFunction(); }); } }; myObj.render(); //----------------------------------------------------- var myObj = { specialFunction: function () { }, anotherSpecialFunction: function () { }, getAsyncData: function (cb) { cb(); }, render: function () { this.getAsyncData(function () { this.specialFunction(); this.anotherSpecialFunction(); }.bind(this)); } }; myObj.render(); //----------------------------------------------------- Function.prototype.bind() 内部工作原理: Function.prototype.bind = function (scope) { var fn = this; return function () { return fn.apply(scope); }; } //----------------------------------------------------- var foo = { x: 3 } var bar = function(){ console.log(this.x); } bar(); // undefined var boundFunc = bar.bind(foo); boundFunc(); // 3
参考:http://blog.jobbole.com/58032/
标签:
原文地址:http://www.cnblogs.com/pengjielee/p/4441103.html