JavaScript原型链中的方法继承

Joe*_*ang 7 javascript javascript-objects

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

总而言之,我总是认为上面的话甚至是现实,所以我做了一些测试来验证它,我打算定义下面的对象关系.请检讨一下.

在此输入图像描述

代码应如下所示.

        //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);
Run Code Online (Sandbox Code Playgroud)

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

Jos*_*eph 5

你刚刚覆盖Rectangle.prototype了已有的东西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);
Run Code Online (Sandbox Code Playgroud)

在添加原型对象之前,首先创建原型对象.

Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.move = function (x, y) {
  this.x += x;
  this.y += y;
  alert('Rectangle move');
};
Run Code Online (Sandbox Code Playgroud)