小程序原型图:JavaScript:解释继承__proto__和原型的图

关于小程序原型图的问题,在javascript diagram中经常遇到, 我有以下代码:

我有以下代码:

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如何从Shape继承describeLocation()方法

为什么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

15

Diagram Full-size — image, page.

Circle.prototype(原始)是作为function Circle(...) {...}的副作用创建的

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

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

Animated diagram Full-size — image, page.

0

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

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

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(去引用它)来更改 org 名称时,copy1 和 org 不再指向同一对象。

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

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(726)
Chunk.js:构建nextjs应用程序后 chunk/pages/_app-.....js文件大小太大
上一篇
Php代码运行:使用AJAX运行PHP代码
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(19条)