javascript之bind
来源:广州中睿信息技术有限公司官网
发布时间:2012/10/21 23:25:16 编辑:editor 阅读 295
前几天看到一个面试题,题目是这样的:请你说说对javascript中apply,call,bind的理解?首先apply和call是老生常谈的东西,但是对于bind,我愣了下,因为这个词是jquer

前几天看到一个面试题,题目是这样的:

请你说说对javascript中apply,call,bind的理解?

首先apply和call是老生常谈的东西,但是对于bind,我愣了下,因为这个词是jquery中使用频率很高的一个方法,用来给DOM元素绑定事件用的。

为了搞清这个陌生又熟悉的bind,google一下,发现javascript1.8.5版本中原生实现了此方法,目前IE9+,ff4+,chrome7+支持此方法,opera和safari不支持(MDN上的说明)。

bind的作用和apply,call类似都是改变函数的execute context,也就是runtime时this关键字的指向。但是使用方法略有不同。一个函数进行bind后可稍后执行。

例子如下:

var person = {      name: 'Andrew',      job: 'web front end developer',      gender: 'male',      sayHello: function() {          return 'Hi, I am ' + this.name + ', a ' + this.job;      }  }        console.log(person.sayHello());  // Hi, I am Andrew, a web front end developer    var anotherGuySayHello = person.sayHello.bind({      name:'Alex',      job: 'back end C# developer'  });    console.log(anotherGuySayHello()); // Hi, I am Alex, a back end C# developer  

另外带有参数的例子:

function add(arg1, arg2, arg3, arg4) {      return arg1 + ' ' + arg2 + ' ' + arg3 + ' ' + arg4;  }  var addMore = add.bind({}, 'a', 'b');    console.log(addMore('c', 'd'));  // a b c d  

如果你的浏览器暂时不支持此方法,但你又觉得这个很cool,想用,MDN上也给出参考实现, 这个实现很有意思,代码如下:

if(!Function.prototype.bind) {      Function.prototype.bind = function(oThis) {          if(typeof this !== 'function') {              throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');          }                    var fSlice = Array.prototype.slice,              aArgs = fSlice.call(arguments, 1),              fToBind = this,              fNOP = function() {},              fBound = function() {                  return fToBind.apply(this instanceof fNOP ? this : oThis || window, aArgs.concat(fSlice.call(arguments)));              };                    fNOP.prototype = this.prototype;          fBound.prototype = new fNOP();                return fBound;      };  }  

最后几行代码,通过prototype chain的方式,其中fBound是调用bind函数的子类,为什么这么实现,可以仔细看 fBound = function(){ return ... }这一部分,其中this是运行时决定的,这里主要考虑到如果用new的方式来调用函数(构造函数方式)的情况。

下面的例子,就能很好的说明这点,为了方便说明,此例子直接来自MDN:

function Point(x,y) {      this.x = x;      this.y = y;  }    Point.prototype.toString = function() {      return this.x + ',' + this.y;  };    var p = new Point(1, 2);  p.toString();  // 1,2    var emptyObj = {};  var YAxisPoint = Point.bind(emptyObj, 0);    var axisPoint = new YAxisPoint(5);  axisPoint.toString();  // 0, 5    axisPoint instanceof Point;     // true  axisPoint instanceof YAxisPoint;   // true  

最后给出文章链接,方便您进一步了解

MDN:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
MSDN:
http://msdn.microsoft.com/en-us/library/ff841995%28v=vs.94%29.aspx
联系我们CONTACT 扫一扫
愿景:成为最专业的软件研发服务领航者
中睿信息技术有限公司 广州•深圳 Tel:020-38931912 务实 Pragmatic
广州:广州市天河区翰景路1号金星大厦18层中睿信息 Fax:020-38931912 专业 Professional
深圳:深圳市福田区车公庙有色金属大厦509~510 Tel:0755-25855012 诚信 Integrity
所有权声明:PMI, PMP, Project Management Professional, PMI-ACP, PMI-PBA和PMBOK是项目管理协会(Project Management Institute, Inc.)的注册标志。
版权所有:广州中睿信息技术有限公司 粤ICP备13082838号-2