Javascript - 创建的第二个对象与第一个对象不同
在此处得到的父级Shape
及其子级Rectangle
。 当我创建几个Rectangle
对象问题发生 - 第一个有draw
功能,但其他人不是!它甚至还有其他类型(Object
和Shape
)Javascript - 创建的第二个对象与第一个对象不同
为什么会发生这种情况?
这里是代码
index.html
<html>
<head>
<title>TODO supply a title</title>
</head>
<body>
<div>TODO write content</div>
<script type="text/javascript" src="Rect.js"></script>
<script type="text/javascript" src="Shape.js"></script>
<script type="text/javascript" src="Main.js"></script>
</body>
</html>
Shape.js
function Shape(center){
this.center = center;
this.angle = 0;
}
[R ect.js
var Rectangle = function(center, width,height){
Shape.call(this, center);
this.mType = "Rectangle";
this.mWidth = width;
this.mHeight = height;
var prototype = Object.create(Shape.prototype);
prototype.constructor = Rectangle;
Rectangle.prototype = prototype;
};
Rectangle.prototype.draw = function() {
//for the test
console.log("Rect is drawn");
};
问题是,每当您拨打Rectangle
的构造函数时,都会创建一个新的Rectangle.prototype
,它将替换旧的。但是您仅将draw
方法添加到第一个Rectangle.prototype
。
你不应该在构造函数中创建原型链,你应该设置它一次。
function Shape(center){
this.center = center;
this.angle = 0;
}
function Rectangle(center, width,height){
Shape.call(this, center);
this.mType = "Rectangle";
this.mWidth = width;
this.mHeight = height;
};
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.draw = function() {
//for the test
console.log("Rect is drawn");
};
Rectangle.prototype.constructor = Rectangle;
var up = new Rectangle(1, 1, 3);
var down = new Rectangle(2, 1, 3);
up.draw();
down.draw();
console.log(Shape.prototype.isPrototypeOf(up));
console.log(down instanceof Shape);
哦,现在我明白了!谢谢 – DanilGholtsman
但是,当我们尝试'up.isPrototypeOf(Shape);'(或)'down.isPrototypeOf(Shape);'它仍然会说'false'。为什么? –
我认为它应该是'Shape.isPrototypeOf(up)' – Barmar
其实你需要删除(或),您做了前行的“反向”发表意见Rectangle.prototype = prototype;
语句进行Rect.js
文件。
Rect.js
var Rectangle = function(center, width,height){
Shape.call(this, center);
this.mType = "Rectangle";
this.mWidth = width;
this.mHeight = height;
var prototype = Object.create(Shape.prototype);
prototype.constructor = Rectangle;
// Comment the below line, to make your code work.
//Rectangle.prototype = prototype;
};
希望这有助于!
如果他这样做,他如何从'Shape'继承'Rect'? – Barmar
嗨Barmar,我的回答更接近消除错误 –
并且当我们尝试'up.isPrototypeOf(Shape);'(或者)我的方式来评论'Rectangle.prototype ...' )'down.isPrototypeOf(Shape);'它仍然说错误。 –
每当你创建一个'Rectangle',创建一个新的'prototype'。但是你只定义了一次'Rectangle.prototype.draw'。 – Barmar
@Barmar所以我第一次到达'draw'它创建的时候,只是在调用构造函数之后呢? – DanilGholtsman