【问题标题】:JavaScript ineritance. How is it working in the sample code shown?JavaScript 继承。它在显示的示例代码中是如何工作的?
【发布时间】:2015-12-21 06:36:19
【问题描述】:

以下链接包含我在此处显示的示例代码(cmets 是我的)。

2ality

代码sn-p:

function Point(x, y) {
    this.x = x;
    this.y = y;
}

function ColorPoint(x, y, color) {
    Point.call(this, x, y);
    this.color = color;
}

function inherits(SubC, SuperC) {
    var subProto = Object.create(SuperC.prototype);
    // At the very least, we keep the "constructor" property
    // At most, we preserve additions that have already been made
    extend(subProto, SubC.prototype);
    SubC.prototype = subProto;
    SubC._super = SuperC.prototype;
}

function extend(target, source) {
    Object.getOwnPropertyNames(source)
        .forEach(function(property) {
            Object.defineProperty(target, property,
                Object.getOwnPropertyDescriptor(source, property));
        });
    return target;
}

Point.prototype.toString = function() {
    return "(" + this.x + "," + this.y + ")";
};

ColorPoint.prototype.toString = function() {
    return this.color + " " + Point.prototype.toString.call(this);
};

console.log(Point);
console.log(ColorPoint);

inherits(ColorPoint, Point);

console.log(ColorPoint.prototype); //Refers to the object from which all the instances are created from

console.log(ColorPoint.prototype.constructor); //The function itself

var greenPoint = new ColorPoint(1, 2, "Green");

console.log(greenPoint);

console.log(greenPoint.prototype); //Undefined. Objects have no prototype property

console.log(greenPoint.constructor); // greenPoint as an object has constructor, from which it is created i.e. function ColorPoint

console.log(greenPoint.constructor.prototype); //The constructor ColorPoint

我无法理解继承方法在这里所做的事情。我非常了解它是如何使用以下策略的。

ColorPoint.prototype = Object.create(Point.prototype);//Point prototype is referenced to ColorPoints'
ColorPoint.prototype.constructor = ColorPoint;//Reset constructor

但我不明白为什么subProto.constructor 指的是ColorPoint。接下来,为什么extend方法参数没有像ColorPoint、Point(child, parent)那样分别传递。

【问题讨论】:

    标签: javascript function inheritance constructor prototype


    【解决方案1】:

    当您使用 new ColorPoint() 从构造函数创建实例时,ColorPoint.prototype.constructor 属性将指向构造函数 --> ColorPoint。

    当您使用ColorPoint.prototype = Object.create 时,您会使用 Point 构造函数覆盖构造函数,这只是将其设置回正确的函数。

    在 extend 方法中,来自 source 对象的所有属性都被传递给 target

    【讨论】:

      猜你喜欢
      • 2017-01-29
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多