gpt4 book ai didi

javascript - 关于理解绑定(bind)和继承的相关性

转载 作者:行者123 更新时间:2023-11-28 04:25:01 26 4
gpt4 key购买 nike

今天我正在阅读关于 Function.prototype.bind() 的 MDN 文档。在Bound functions used as constructors部分下有一个例子我不太明白。

我在 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

我可以清楚地明白为什么 axisPointPointYAxisPoint 的实例。但是 new Point(17,42) 到底怎么能成为 YAxisPoint 的实例呢?

最佳答案

But how in the world can new Point(17,42) be an instance of YAxisPoint?

因为 instanceof 对于绑定(bind)函数(通过 .bind() 调用创建的函数)有特殊的作用。通常它会检查对象是否继承自构造函数.prototype,但绑定(bind)函数没有.prototype。相反,当您在绑定(bind)函数上使用 instanceof 时,它会检查该对象是否是目标函数(调用了 bind())的实例。所以

… instanceof YAxisPoint

完全等同于

… instanceof Point

您可以在规范中检查这一点( ES5ES6 )。

关于javascript - 关于理解绑定(bind)和继承的相关性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45134471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com