在此示例中:

/**
 * Transform base class
 */
function Transform() {
    this.type = "2d";
}

Transform.prototype.toString = function() {
    return "Transform";
}

/**
 * Translation class.
 */
function Translation(x, y) {
    // Parent constructor
    Transform.call(this);

    // Public properties
    this.x = x;
    this.y = y;
}

// Inheritance
Translation.prototype = Object.create(Transform.prototype);
// Here I purposely omit Translation.prototype.constructor = Translation;

translation = new Translation(10, 15);

console.log(Translation.prototype.constructor); // Transform
console.log(translation.__proto__); // Transform
console.log(translation.constructor); // Transform

// Yet this is true!
console.log(translation instanceof Translation);


有人可以解释为什么translation instanceof Translationtrue都不包含__proto__的原因为什么constructorTranslation吗?

最佳答案

这是真的,因为translationTranslation的实例。通常,new X instanceof X为true。

从算法上讲是正确的,因为Translation.prototype === Object.getPrototypeOf( translation ),这就是instanceof运算符要测试的内容。

它从那里开始,一直到原型链,因此translation instanceof Transform也是正确的,因为:

Transform.prototype === Object.getPrototypeOf( Object.getPrototypeOf( translation ) )


translation instanceof Object也是正确的,因为:

Object.prototype === Object.getPrototypeOf( Object.getPrototypeOf( Object.getPrototypeOf( translation ) ) )

关于javascript - 不完全继承时的行为实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57576833/

10-10 23:18