我有以下代码:
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);
引起的变化
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,我发现这些问题中的图表非常有帮助:1,2,3,4。
为什么 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 仍然指向同一个对象。
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(19条)