Today I was reading the MDN documentation on Function.prototype.bind() . Under the section Bound functions used as constructors there is an example that I cannot quite understand.
I ran the following piece of code both in Node.js (v.4.4.5) and 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
I can clearly see why axisPoint
is an instance of both Point
and YAxisPoint
. But how in the world can new Point(17,42)
be an instance of YAxisPoint
?
But how in the world can
new Point(17,42)
be an instance ofYAxisPoint
?
Because instanceof
works special with bound functions (those created from .bind()
calls). Usually it would check whether the object inherits from the constructors .prototype
, but bound functions don't have a .prototype
. Instead, when you use instanceof
on a bound function, it checks whether the object is an instance of the target function (that bind()
was called upon). So
… instanceof YAxisPoint
is exactly equivalent to
… instanceof Point
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.