这里有父类Shape
及其子Rectangle
。
当我创建一些Rectangle
对象问题时 - 第一个有draw
函数,但其他的不是!它甚至还有其他类型(Object
vs Shape
)
为什么会这样?
这是代码
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;
}
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;
Rectangle.prototype = prototype;
};
Rectangle.prototype.draw = function () {
//for the test
console.log("Rect is drawn");
};
答案 0 :(得分:2)
问题在于,每次调用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);
。
你不应该在构造函数中创建原型链,你应该设置一次。
cat incorrect.patch | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g" > correct.patch
&#13;
上的示例
答案 1 :(得分:1)
实际上,您需要删除(或)评论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;
};
希望这有帮助!