JavaScript原型链中的方法继承

时间:2013-05-15 09:26:58

标签: javascript javascript-objects

在javascript中,每个对象都有一个创建它的对象的秘密链接,形成一个链。当一个对象被要求提供它没有的属性时,会询问它的父对象......直到找到属性或直到达到根对象为止。

所有,我总是认为上面的话甚至是现实,所以我做了一些测试来验证它,我打算定义下面的对象关系。请查看它。

enter image description here

代码应如下所示。

        //Shape - superclass
        function Shape() {
          this.x = 0;
          this.y = 0;
        };

        Shape.prototype.move = function(x, y) {
            this.x += x;
            this.y += y;

            alert('Shape move');
        };

        // Rectangle - subclass
        function Rectangle() {
          Shape.call(this); //call super constructor.
        }

        Rectangle.prototype.move = function(x, y) {
            this.x += x;
            this.y += y;

            alert('Rectangle move');
        };

        // Square - subclass
        function Square(){
            Shape.call(this);
        }

        Rectangle.prototype = Object.create(Shape.prototype);
        Square.prototype=Object.create(Rectangle.prototype);

        var rect = new Rectangle();

        var sq= new Square();

        sq.x=1;
        sq.y=1;
        sq.move(1,1);

由于在move中找不到Square.prototype方法,所以JavaScript会在链后面的父对象中找到它,我原以为它会在{{1}中找到},但实际上它位于根Rectangle.prototype中,所以我无法理解为什么Shape.prototype实际调用sq.move(1,1)而不是调用Shape.prototype.move方法{ {1}}?我错过了什么吗?谢谢。

2 个答案:

答案 0 :(得分:5)

您刚刚覆盖已Rectangle.prototype的{​​{1}}。由于您已覆盖它,因此您附加的move不再存在,这就是使用move移动的原因。

Shape

首先创建原型对象,然后再添加它。

Rectangle.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  alert('Rectangle move');
};

function Square(){
  Shape.call(this);
}

//overwritten the prototype
Rectangle.prototype = Object.create(Shape.prototype);

答案 1 :(得分:2)

向下移动原型扩展。 现在,您在扩展原型后分配原型,因此它将覆盖扩展原型

//Shape - superclass
        function Shape() {
          this.x = 0;
          this.y = 0;
        };
        // Rectangle - subclass
        function Rectangle() {
          Shape.call(this); //call super constructor.
        }
        // Square - subclass
        function Square(){
            Shape.call(this);
        }    

        Rectangle.prototype = Object.create(Shape.prototype);
        Square.prototype = Object.create(Rectangle.prototype);

        Shape.prototype.move = function(x, y) {
            this.x += x;
            this.y += y;

            alert('Shape move');
        };
        Rectangle.prototype.move = function(x, y) {
            this.x += x;
            this.y += y;

            alert('Rectangle move');
        };

        var rect = new Rectangle();
        var sq = new Square();

        sq.x=1;
        sq.y=1;
        sq.move(1,1);