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

时间:2017-03-09 07:05:48

标签: javascript html oop prototype

这里有父类Shape及其子Rectangle。 当我创建一些Rectangle对象问题时 - 第一个有draw函数,但其​​他的不是!它甚至还有其他类型(Object vs Shape

为什么会这样?

这是错误 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;
}

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

2 个答案:

答案 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);

你不应该在构造函数中创建原型链,你应该设置一次。

&#13;
&#13;
cat incorrect.patch | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g" > correct.patch
&#13;
&#13;
&#13;

请参阅Inheritance and the prototype chain

上的示例

答案 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;
};

希望这有帮助!