Javascript - 创建的第二个对象与第一个对象不同

问题描述:

在此处得到的父级Shape及其子级Rectangle。 当我创建几个Rectangle对象问题发生 - 第一个有draw功能,但其他人不是!它甚至还有其他类型(ObjectShapeJavascript - 创建的第二个对象与第一个对象不同

为什么会发生这种情况?

以下是错误 enter image description here enter image description here

这里是代码

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"); 
}; 
+0

每当你创建一个'Rectangle',创建一个新的'prototype'。但是你只定义了一次'Rectangle.prototype.draw'。 – Barmar

+0

@Barmar所以我第一次到达'draw'它创建的时候,只是在调用构造函数之后呢? – DanilGholtsman

问题是,每当您拨打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);

见的例子在Inheritance and the prototype chain

+0

哦,现在我明白了!谢谢 – DanilGholtsman

+1

但是,当我们尝试'up.isPrototypeOf(Shape);'(或)'down.isPrototypeOf(Shape);'它仍然会说'false'。为什么? –

+1

我认为它应该是'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; 
}; 

希望这有助于!

+0

如果他这样做,他如何从'Shape'继承'Rect'? – Barmar

+0

嗨Barmar,我的回答更接近消除错误 –

+0

并且当我们尝试'up.isPrototypeOf(Shape);'(或者)我的方式来评论'Rectangle.prototype ...' )'down.isPrototypeOf(Shape);'它仍然说错误。 –