Skip to content

Instantly share code, notes, and snippets.

@ssdemajia
Created July 16, 2018 11:29
Show Gist options
  • Save ssdemajia/c66547edd321215fed0ebe657f4402e7 to your computer and use it in GitHub Desktop.
Save ssdemajia/c66547edd321215fed0ebe657f4402e7 to your computer and use it in GitHub Desktop.
Javascript硬绑定函数
function bind(func, obj) {
return function() {
return func.apply(obj, arguments);
};
}
// 使用
// 比如一开始有一个函数
function foo(something) {
console.log(this.a, something);
return this.a + something;
}
// 有一个对象
var obj = {
a: 123
}
// 将foo绑定到obj上
var fooBind = bind(foo, obj);
// 此时的fooBind就相当于一个新的foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment