JavaScript:解释继承的图表,__ proto__和原型 [英] JavaScript: Diagram to explain inheritance, __proto__ and prototype
本文介绍了JavaScript:解释继承的图表,__ proto__和原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
function Shape(x,y){
this.x = x ;
this.y = y;
}
Shape.prototype.describeLocation = function(){
返回'我位于'+ this.x +','+ this.y;
};
var myShape = new Shape(1,2);
函数Circle(x,y,radius){
Shape.call(this,x,y); //调用父构造函数
this.radius = radius;
}
var myFirstCircle = new Circle(3,4,10);
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.calculateArea = function(){
返回'我的区域是'+(Math.PI * this.radius * this.radius);
};
var mySecondCircle = new Circle(3,4,10);
我想要一个视觉*解释:
- 由
Circle.prototype = Object.create(Shape.prototype)引起的变化;
-
,,页面。I have the following code:
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);
I'd like a visual* explanation of:
- the changes caused by
Circle.prototype = Object.create(Shape.prototype);
- the
__proto__
andprototype
connections between the objects - how
mySecondCircle
inherits thedescribeLocation()
method fromShape
- why the
calculateArea()
method exists formySecondCircle
but not formyFirstCircle
:
> myFirstCircle.calculateArea() Uncaught TypeError: undefined is not a function > mySecondCircle.calculateArea() "My area is 314.1592653589793"
* When trying to understand JavaScript issues regarding inheritance, a diagram really is worth a thousand words, and I've found the diagrams in these questions very helpful: 1, 2, 3, 4.
解决方案Circle.prototype (original) is created as a side-effect of
function Circle(...) {...}
Circle.prototype (redefined) is created by
Circle.prototype = Object.create(Shape.prototype);
I also made this animated version to show the order in which the objects are created:
这篇关于JavaScript:解释继承的图表,__ proto__和原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- the changes caused by
查看全文