Tac*_*tex 4 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);
Run Code Online (Sandbox Code Playgroud)
我想要一个视觉*解释:
Circle.prototype = Object.create(Shape.prototype);__proto__和
prototype
中的对象之间的连接mySecondCircle继承describeLocation()方法ShapecalculateArea()方法存在mySecondCircle但不适用于myFirstCircle:> myFirstCircle.calculateArea()
Uncaught TypeError: undefined is not a function
> mySecondCircle.calculateArea()
"My area is 314.1592653589793"
Run Code Online (Sandbox Code Playgroud)
*如果想了解关于继承的JavaScript的问题,图真的是 胜过千言万语,我已经发现了这些问题的图表非常有帮助: 1, 2, 3, 4.
| 归档时间: |
|
| 查看次数: |
1677 次 |
| 最近记录: |