今天我正在阅读 MDN 文档Function.prototype.bind()。在该部分下用作构造函数的绑定函数有一个例子我不太理解。
我在 Node.js (v.4.4.5) 和 Google Chrome (v58.0.3029.81) 中运行了以下代码
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, 1/*x*/);
var axisPoint = new YAxisPoint(5);
console.log(axisPoint.toString()); // '1,5'
console.log(axisPoint instanceof Point); // true
console.log(axisPoint instanceof YAxisPoint); // true
console.log(new Point(17, 42) instanceof YAxisPoint); // true
我可以清楚地看到为什么axisPoint
是两者的一个实例Point
and YAxisPoint
。但这世上怎能new Point(17,42)
是一个实例YAxisPoint
?
但这世上怎能new Point(17,42)
是一个实例YAxisPoint
?
Because instanceof
与绑定函数(从创建的函数.bind()
来电)。通常它会检查对象是否继承自构造函数.prototype
,但绑定函数没有.prototype
。相反,当您使用instanceof
在绑定函数上,它检查该对象是否是目标函数的实例(即bind()
被呼吁)。所以
… instanceof YAxisPoint
完全等于
… instanceof Point
您可以在规格中检查这一点(ES5, ES6).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)