
函数绑定Function-prototype-bind
-
将函数绑定到指定环境
1
2
3
4
5
6Function.prototype.bind = function(scope){
var fn = this;
return function(){
return fn.apply(scope);
}
} -
举例1
1
2
3
4
5
6
7
8
9
10
11
12
13
14this.x = 9; // this refers to global "window" object here in the browser
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var retrieveX = module.getX;
retrieveX();
// 9
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81 -
举例2
1
2
3
4
5
6
7
8
9
10
11
12
13var foo = {
x: 3
}
var bar = function(){
console.log(this.x);
}
bar(); // undefined
var boundFunc = bar.bind(foo);
boundFunc(); // 3




近期评论