js原生函数bind

[javascript]  view plain copy
  1. 在javascript中,函数总是在一个特殊的上下文执行(称为执行上下文),如果你将一个对象的函数赋值给另外一个变量的话,这个函数的执行上下文就变为这个变量的上下文了。下面的一个例子能很好的说明这个问题  
  2. 代码如下:  
  3.   
  4. window.name = "the window object"   
  5. function scopeTest() {   
  6.     return this.name;   
  7. }   
  8. // calling the function in global scope:   
  9. scopeTest()   
  10. // -> "the window object"   
  11. var foo = {   
  12.     name: "the foo object!",   
  13.     otherScopeTest: function() { return this.name }   
  14. };   
  15. foo.otherScopeTest();// -> "the foo object!"   
  16. var foo_otherScopeTest = foo.otherScopeTest;   
  17. foo_otherScopeTest();   
  18. // –> "the window object"   
  19.   
  20. 如果你希望将一个对象的函数赋值给另外一个变量后,这个函数的执行上下文仍然为这个对象,那么就需要用到bind方法。   
  21. bind的实现如下:   
  22. 复制代码 代码如下:  
  23.   
  24. // The .bind method from Prototype.js   
  25. Function.prototype.bind = function(){   
  26. var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();   
  27. return function(){   
  28. return fn.apply(object,   
  29. args.concat(Array.prototype.slice.call(arguments)));   
  30. };   
  31. };   
  32.   
  33. 使用示例:   
  34. 复制代码 代码如下:  
  35.     
  36.   var obj = {   
  37.     name: 'A nice demo',   
  38.     fx: function() {   
  39.         alert(this.name);   
  40.     }   
  41.   };   
  42.   
  43.   window.name = 'I am such a beautiful window!';   
  44.   
  45.   function runFx(f) {   
  46.     f();   
  47.   }   
  48.   function fx(){  
  49.     alert(this.name);    
  50.   }  
  51.   var fx2 = obj.fx.bind(obj);   
  52.   runFx(obj.fx); // I am such a beautiful window!  
  53.   runFx(fx2); // A nice demo  
  54.   runFx(fx);// I am such a beautiful window!  

猜你喜欢

转载自blog.csdn.net/liuchaoxuan/article/details/81038346
今日推荐