JavaScript 中 bind 方法的作用与实现原理

作者:纸飞机时间:2026-10-26 16:24:26浏览:445

本文介绍 JavaScript 中 bind 函数的核心作用,即解决函数赋值后执行上下文丢失的问题。通过解析 Prototype.js 的实现源码及自定义简单实现,展示如何利用闭包保存 this 指向,并结合 console.assert 验证绑定前后的行为差异。

代码如下:

 
JavaScript 执行上下文与 this 指向问题window.name = "the window object"
function scopeTest() {
return this.name;
} 
// 在全局作用域中调用该函数:
scopeTest()
// 输出结果为 "the window object"
var foo = {
name: "the foo object!",
otherScopeTest: function() { return this.name }
}; 
foo.otherScopeTest(); // 输出结果为 "the foo object!"
var foo_otherScopeTest = foo.otherScopeTest;
foo_otherScopeTest();
// 输出结果为 "the window object"

当需要将一个对象的方法赋值给另一个变量,并期望该方法在执行时仍保持原有的对象上下文时,就需要使用 bind 方法。


bind 方法的实现原理

其实现原理如下:


代码如下:

 
// 来自 Prototype.js 的 .bind 方法实现
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
}; 
}; 

使用示例:


bind 使用示例与验证

代码如下:

 
var obj = {
name: 'A nice demo',
fx: function() {
alert(this.name);
} 
}; 
window.name = 'I am such a beautiful window!';
function runFx(f) {
f();
} 
var fx2 = obj.fx.bind(obj);
runFx(obj.fx);
runFx(fx2);

参考:


http://www.prototypejs.org/api/function/bind


PS:


刚刚发现 Prototype.js 的 API 文档解释得非常详细,值得花时间仔细阅读。


我的简单实现:


代码如下:

 
Function.prototype.bind = function(obj) {
var _this = this;
return function() {
return _this.apply(obj,
Array.prototype.slice.call(arguments));
} 
} 
var name = 'window',
foo = {
name:'foo object',
show:function() {
return this.name;
} 
}; 
console.assert(foo.show()=='foo object',
'expected foo object,actual is '+foo.show());
var foo_show = foo.show;
console.assert(foo_show()=='window',
'expected is window,actual is '+foo_show());
var foo_show_bind = foo.show.bind(foo);
console.assert(foo_show_bind()=='foo object',
'expected is foo object,actual is '+foo_show_bind());
作者最新文章