nbagonet
7/6/2016 - 7:05 AM

Function.prototype.bind

Function.prototype.bind

// 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 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;
//   };
// };

Function.prototype.bind = function (scope) {
    var fn = this;
    return function () {
        return fn.apply(scope);
    };
};

<a href="javascript:void(0)" id="test1">不加.bind</a>
<br>
<a href="javascript:void(0)" id="test2">加了.bind</a>

<script>
  var dom1 = document.getElementById('test1');
  dom1.onclick = (function(){
    console.log(this);
  });
  var dom2 = document.getElementById('test2');
  dom2.onclick = (function(){
    console.log(this);
  }).bind(this);
</script>