【发布时间】:2015-12-21 06:36:19
【问题描述】:
以下链接包含我在此处显示的示例代码(cmets 是我的)。
代码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