Javascript中的关键字实例

时间:2018-07-18 12:25:26

标签: javascript

rect是Shape的实例吗? Shape构造函数不在rect的原型链上。

rect.__proto__ : Rectangle.prototype
Rectangle.prototype : Object.prototype

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?', rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'

对象成为构造函数实例的条件是什么?

2 个答案:

答案 0 :(得分:1)

好吧,我明白了。

这是原型链。

rect__proto__: Rectangle. prototype
Rectangle.prototype.__proto__: Shape.prototype

答案 1 :(得分:1)

instanceof运算符测试object.prototype(例如Rectangle)是否在对象的原型链中。

rect instanceof Rectangle

是因为:

Object.getPrototypeOf(rect) === Rectangle.prototype

请在此处查看更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

此外,您可以在标准中跟踪此逻辑: https://www.ecma-international.org/ecma-262/6.0/#sec-function.prototype-@@hasinstance

v instanceof F

评估为

F[@@hasInstance](v)

同时 https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance

4. Let P be Get(C, "prototype")
7.a Let O be O.[[GetPrototypeOf]]().
7.d If SameValue(P, O) is true, return true.