JavaScript:解释继承的图表,__ proto__和原型

时间:2015-03-19 22:14:04

标签: javascript inheritance prototype

我有以下代码:

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

Shape.prototype.describeLocation = function() {
    return 'I am located at ' + this.x + ', ' + this.y;
};

var myShape = new Shape(1, 2);

function Circle(x, y, radius) {
    Shape.call(this, x, y);  // call parent constructor
    this.radius = radius;
}

var myFirstCircle = new Circle(3, 4, 10);

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

Circle.prototype.calculateArea = function() {
    return 'My area is ' + (Math.PI * this.radius * this.radius);
};

var mySecondCircle = new Circle(3, 4, 10);

我想要一个视觉*解释:

  • Circle.prototype = Object.create(Shape.prototype);
  • 引起的更改
  • __proto__prototype 对象之间的联系
  • mySecondCircle如何从describeLocation()
  • 继承Shape方法
  • 为什么calculateArea()方法适用于mySecondCircle而不适用于myFirstCircle

> myFirstCircle.calculateArea()
Uncaught TypeError: undefined is not a function

> mySecondCircle.calculateArea()
"My area is 314.1592653589793"

*当试图理解有关继承的JavaScript问题时,图表确实如此 worth a thousand words, 我发现这些问题中的图表非常有用: 1234

2 个答案:

答案 0 :(得分:12)

Diagram 全尺寸 - imagepage

Circle.prototype(原创)是作为function Circle(...) {...}

的副作用而创建的

Circle.prototype(重新定义)Circle.prototype = Object.create(Shape.prototype);

创建

我也制作了这个动画版本来显示创建对象的顺序:

Animated diagram 全尺寸 - imagepage

答案 1 :(得分:0)

  

为什么calculateArea()方法存在于mySecondCircle而不存在于myFirstCircle:

通过重新分配Circle.prototype,您将引用已创建的实例使用的原型。以下代码演示:

var org = {name:"org"}
var copy1 = org;//copy1===org
org={name:"changed"};org!==copy1
var copy2 = org;//copy2===org
org.name="again";//copy2.name === "again"

当我们通过为org(取消引用它)指定一个完全不同的对象来更改组织名称时,copy1和org不再指向同一个对象。

当我们设置org(mutate org)的name属性时,copy2和org仍然指向同一个对象。

相关问题