为什么在JavaScript中将object和constructor.prototype设置为Base?
这是我的小程序。当我在调试模式下检查rec的值时,对象是Base{x=0,y=0,w=10,more…}。它应该是长方形的吗?此外,constructor.prototype是基础。为什么不塑造呢为什么在JavaScript中将object和constructor.prototype设置为Base?,javascript,Javascript,这是我的小程序。当我在调试模式下检查rec的值时,对象是Base{x=0,y=0,w=10,more…}。它应该是长方形的吗?此外,constructor.prototype是基础。为什么不塑造呢 function Base() { } function Shape(x, y) { this.x = x; this.y = y; } Shape.prototype = new Base(); Shape.prot
function Base() {
}
function Shape(x, y) {
this.x = x;
this.y = y;
}
Shape.prototype = new Base();
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.log("x = " + this.x + " y = " + this.y);
};
function Rectangle(x, y, w, h) {
Shape.call(this, x, y);
this.w = w;
this.h = h;
}
Rectangle.prototype = new Shape();
Rectangle.prototype.area = function() {
return this.w * this.h;
};
var rec = new Rectangle(0, 0, 10, 10);
console.log(instanceOf(rec, Rectangle));
function instanceOf(object, constructor) {
while (object != null) {
if (object == constructor.prototype)
return true;
if ( typeof object == 'xml') {
return constructor.prototype == XML.prototype;
}
object = object.__proto__;
}
return false;
}
看一看。您可能不会使用它并创建它的新实例,而只是从Base.prototype
继承
此外,constructor.prototype是基础。为什么不塑造呢
function Base() {
}
function Shape(x, y) {
this.x = x;
this.y = y;
}
Shape.prototype = new Base();
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.log("x = " + this.x + " y = " + this.y);
};
function Rectangle(x, y, w, h) {
Shape.call(this, x, y);
this.w = w;
this.h = h;
}
Rectangle.prototype = new Shape();
Rectangle.prototype.area = function() {
return this.w * this.h;
};
var rec = new Rectangle(0, 0, 10, 10);
console.log(instanceOf(rec, Rectangle));
function instanceOf(object, constructor) {
while (object != null) {
if (object == constructor.prototype)
return true;
if ( typeof object == 'xml') {
return constructor.prototype == XML.prototype;
}
object = object.__proto__;
}
return false;
}
我不确定您在这里指的是哪个构造函数
:
- 所有对象的
属性都是constructor
,因为它们都从Base
对象继承了这个原型。设置继承链后,您没有覆盖它。这不是真的需要,而是很好的样式:Base.prototype
和Shape.prototype.constructor=Shape
——其中这些原型对象是从Rectangle.prototype.constructor=Rectangle
基继承的覆盖对象
- 函数的
实例的
构造函数
参数。您在那里传入
,因此Rectangle
是构造函数。prototype
的原型对象,它继承自Rectangle
,但不同Base
Base
是否是特殊的对象,例如宿主对象?您的rec
对象是Base
的一个实例,因此它的显示可能会有所不同
rec
只是一个从矩形继承的对象。prototype
从形状继承。prototype
从基继承。prototype
从… 假设Base
是您从继承自null
的Object.prototype
中定义的函数,这可能是因为Rectangle.prototype.constructor
是Base
。constructor.prototype也是Base。您必须重定向构造函数,如Rectangle.prototype.constructor=Rectangle
注意,对于本机对象,typeof object==“xml”
永远不会为真。在Firefox 17中,它可能会覆盖其函数中的object
值,因此它可能是xml
或其他任何东西。是的,它在添加构造函数后工作:Shape.prototype.constructor=Shape和Rectangle.prototype.constructor=Rectangle。我还有一个问题:为什么rec是一个函数,而不是一个对象?在调试控制台中,是函数{x=0,y=0,w=10,more…}还有一个问题:更改后,rec.\uuuu proto\uuu.property变成一个无止境的矩形链。原型矩形(x,y,w,h)原型矩形(x,y,w,h)原型矩形(x,y,w,h)原型矩形(x,y,w,h)原型矩形(x,y,w,h)原型矩形(x,y,w,h)在我的构造函数任务中我错过了新的。它现在工作得很好。谢谢