本文深入解析JavaScript中Function.prototype.bind()方法的核心机制。通过实例说明bind如何固定this指向、实现偏函数参数预绑定及与setTimeout配合管理实例状态。重点剖析bind在ECMA-262第五版中的实现原理,涵盖简单作用域绑定、支持柯里化的参数合并以及利用中转构造函数处理new调用时的原型链传递逻辑,提供兼容浏览器的完整实现方案。
bind()方法引入与this指向问题
在探讨bind()方法的具体用法前,我们先通过一个经典案例来引入话题。
var altwrite = document.write; altwrite("hello"); //1.以上代码有什么问题 //2.正确操作是怎样的 //3.bind()方法怎么实现
上述案例的核心考点在于this的指向问题。直接调用altwrite()时,其内部this会指向全局对象(global或window),从而引发非法调用异常。解决该问题的标准做法是利用bind()方法重新绑定上下文。
altwrite.bind(document)("hello") 此外,也可以采用call()方法达到相同效果:
altwrite.call(document, "hello") 本文的核心内容将聚焦于第三个问题,即深入剖析bind()方法的底层实现原理。在展开实现细节之前,我们先梳理bind()在实际开发中的常见应用场景。
bind()的核心应用场景
绑定函数 bind()最基础的用途是创建一个新函数,该函数在被调用时始终拥有固定的this值。常见的错误操作如前例所示,将对象方法提取后直接调用,若不做特殊处理,原对象的this指向通常会丢失。利用bind()可以优雅地解决这一上下文丢失问题。
this.num = 9;
var mymodule = {
num: 81,
getNum: function() { return this.num; }
};
module.getNum(); // 81
var getNum = module.getNum;
getNum(); // 9, 因为在这个例子中,"this"指向全局对象
// 创建一个'this'绑定到module的函数
var boundGetNum = getNum.bind(module);
boundGetNum(); // 81
偏函数(Partial Functions)
Partial Functions也被称为部分应用(Partial Applications)。以下是关于偏函数的标准定义:
Partial application can be described as taking a function that accepts some number of arguments, binding values to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.
这是一个极具价值的特性。通过bind(),我们可以预先设定函数的部分参数,在后续调用时只需传入剩余参数即可。
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
// 预定义参数37
var leadingThirtysevenList = list.bind(undefined, 37);
var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
和setTimeout一起使用
通常情况下,setTimeout()回调函数中的this会指向window或global对象。当在类的方法中需要使用this指向当前类实例时,可以使用bind()将this绑定到回调函数,从而正确管理实例状态。
function Bloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
// 1秒后调用declare函数
Bloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 1000);
};
Bloomer.prototype.declare = function() {
console.log('我有 ' + this.petalCount + ' 朵花瓣!');
};
注意:对于事件处理函数和setInterval方法,同样可以使用上述绑定技巧。
绑定函数作为构造函数
绑定后的函数同样适用于通过new操作符构造目标函数的实例。需要注意的是,当使用绑定函数进行构造时,bind()绑定的this值会被忽略,但通过bind()传入的预置参数依然有效。
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function() {
return this.x + ',' + this.y;
};
var p = new Point(1, 2);
p.toString(); // '1,2'
var emptyObj = {};
var YAxisPoint = Point.bind(emptyObj, 0/*x*/);
// 实现中的例子不支持,
// 原生bind支持:
var YAxisPoint = Point.bind(null, 0/*x*/);
var axisPoint = new YAxisPoint(5);
axisPoint.toString(); // '0,5'
axisPoint instanceof Point; // true
axisPoint instanceof YAxisPoint; // true
new Point(17, 42) instanceof YAxisPoint; // true
在上述示例中,Point和YAxisPoint共享原型对象,因此使用instanceof运算符进行判断时返回true。
捷径
bind()还可以为需要特定this值的函数创建快捷调用方式。
例如,将类数组对象转换为真正的数组,常见的实现如下:
var slice = Array.prototype.slice;
// ...
slice.call(arguments);
如果使用bind()的话,情况变得更简单:
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);
// ...
slice(arguments);
bind()方法的源码实现原理
实现
从上述小节可以看出,bind()拥有多种应用场景。然而,bind()函数直到ECMA-262第五版才被正式纳入规范;这意味着它可能无法在所有旧版浏览器中运行。因此,我们需要自行实现bind()函数以兼容环境。
首先,我们可以通过为目标函数指定作用域来简单实现bind()方法:
Function.prototype.bind = function(context){
self = this; //保存this,即调用bind方法的目标函数
return function(){
return self.apply(context,arguments);
};
};
考虑到函数柯里化的情况,我们可以构建一个更加健壮的bind():
Function.prototype.bind = function(context){
var args = Array.prototype.slice.call(arguments, 1),
self = this;
return function(){
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return self.apply(context,finalArgs);
};
};
这次的bind()方法不仅可以绑定对象,还支持在绑定时传入参数。
继续,Javascript的函数还可以作为构造函数,那么绑定后的函数用这种方式调用时,情况就比较微妙了,需要涉及到原型链的传递:
Function.prototype.bind = function(context){
var args = Array.prototype.slice(arguments, 1),
F = function(){},
self = this,
bound = function(){
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return self.apply((this instanceof F ? this : context), finalArgs);
};
F.prototype = self.prototype;
bound.prototype = new F();
return bound;
};
这是《JavaScript Web Application》一书中对bind()的实现:通过设置一个中转构造函数F,使绑定后的函数与调用bind()的函数处于同一原型链上,用new操作符调用绑定后的函数,返回的对象也能正常使用instanceof,因此这是最严谨的bind()实现。
对于为了在浏览器中能支持bind()函数,只需要对上述函数稍微修改即可:
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(
this instanceof fNOP && oThis ? this : oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments))
);
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
以上这篇浅析Javascript中bind()方法的使用与实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。