Skip to content

Instantly share code, notes, and snippets.

@cyio
Last active March 14, 2017 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyio/bd17078f271eef9890d048d36ca4a0c4 to your computer and use it in GitHub Desktop.
Save cyio/bd17078f271eef9890d048d36ca4a0c4 to your computer and use it in GitHub Desktop.
实现 bind 方法,用于不支持ES5的浏览器
// Credit to Douglas Crockford for this bind method​
if (!Function.prototype.bind) { // 如果不存在 bind 方法
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") { // bind 方法的调用对象只能是函数,如果不是则抛出异常
// closest thing possible to the ECMAScript 5 internal IsCallable function​
throw new TypeError ("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call (arguments, 1), // 浅复制 bind 的参数,从第 2 个开始到结束 http://stackoverflow.com/a/26618338/5657916
fToBind = this,
fNOP = function () { // 新的空函数
},
fBound = function () { // 要返回的函数,用 apply 方法绑定 this
return fToBind.apply (this instanceof fNOP && oThis // 待返回函数与构造函数原型是否一致,oThis 参数是否存在
? this // 直接使用 bind 的调用对象
: oThis, // 使用指定 this
aArgs.concat (Array.prototype.slice.call (arguments))); // 合并两个方法的参数
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP ();
return fBound;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment