原型继承如何在JS中工作

时间:2018-10-15 01:50:51

标签: javascript

我正在尝试原型继承以计算distance()。但是我遇到了一个错误,TypeError: Cannot read property 'x' of undefined。错误行在代码处标记。我知道我计算distance()的方式是错误的。但是有人可以指导我正确的方法是什么?

'use strict';

 function Shape(x,y){
    this.x = x;
    this.y = y;
  };

  Shape.prototype.distance = function(s1,s2){
    // this.distance = function(s1,s2){
      const xDiff = this.s1.x - this.s2.x;         //error
      const yDiff = this.s1.y - this.s2.y;
      return Math.sqrt(xDiff*xDiff + yDiff*yDiff);      
    // }
  };


 function Circle(x,y,radius){
    Shape.call(this,x,y);
    this.radius = radius;
    this.area = Math.PI*this.radius*this.radius;
};

 function Rectangle(x,y,w,h){
  Shape.call(this,x,y);
  this.width =w;
  this.height =h;
  this.area = this.width * this.height;  
};

Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;

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



const shapes = [
  new Rectangle(3,4,5,6),
  new Circle(0,0,1),
];

shapes.forEach((s) => console.log(s.x, s.y, s.area));
console.log(Shape.prototype.distance(shapes[0],shapes[1]));

1 个答案:

答案 0 :(得分:0)

通常,当您将方法放在原型上时,您会期望在该类的实例上调用该方法。因此,在您的示例中,您将执行以下操作:

 someShape.distance(someOtherShape)

执行此操作时,函数中的this指向调用函数的形状。因此您的距离函数将如下所示:

  Shape.prototype.distance = function(otherShape){
      const xDiff = this.x - otherShape.x;        
      const yDiff = this.y - otherShape.y;
      return Math.sqrt(xDiff*xDiff + yDiff*yDiff);      
  }

然后您可以将其作为对象之一的方法来调用:

function Shape(x, y) {
  this.x = x;
  this.y = y;
}

Shape.prototype.distance = function(otherShape) {
  const xDiff = this.x - otherShape.x; //error
  const yDiff = this.y - otherShape.y;
  return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}

let sh1 = new Shape(0, 0)
let sh2 = new Shape(3, 4)

console.log(sh1.distance(sh2))
// or the opposite
console.log(sh2.distance(sh1))

如果相反,您希望distance是一个类方法,并且要传递两个实例,请不要将函数放在原型上,而是将其添加为函数本身的属性:

function Shape(x,y){
    this.x = x;
    this.y = y;
}
// not on the prototype
Shape.distance = function(s1, s2){
    const xDiff = s1.x - s2.x;         
    const yDiff = s1.y - s2.y;
    return Math.sqrt(xDiff*xDiff + yDiff*yDiff);      
}

let sh1 = new Shape(0, 0)
let sh2 = new Shape(3, 4)
console.log(Shape.distance(sh1, sh2))