Skip to content

Instantly share code, notes, and snippets.

@yardfarmer
Created August 20, 2014 05:06
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 yardfarmer/494aef197ef36b2e3a23 to your computer and use it in GitHub Desktop.
Save yardfarmer/494aef197ef36b2e3a23 to your computer and use it in GitHub Desktop.
Function.prototype.bind 实现方式
/**
* Created by cyk on 14-8-20.
*/
if(!Function.prototype.bind) {
Function.prototype.bind = function(obj) {
"use strict";
// 很巧妙的获取了数组的静态方法 slice
// return a shallow copy of a portion of an array
// slice: arr.slice(begin[,end])
var slice = [].slice,
args = slice.call(arguments, 1), // begin at 1
self = this,
nop = function() {},
bound = function() {
// 这种用法很巧:
// (obj || {}) 如果 obj 不为空,即为 true, 则返回 obj,否则返回 {}
return self.apply.( this instanceof nop ? this : (obj || {}),
// concat 返回一个合并之后的新数组
args.concat(slice.call(arguments))
);
};
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment