JavaScript原型链中的方法继承
“在javascript中,每个对象都有一个指向创建它的对象的秘密链接,形成一个链。当一个对象被要求提供一个它没有的属性时,它的父对象会被要求……不断地向上链,直到找到该属性或到达根对象。” 总之,我一直认为上面的话是事实,即使是现在,所以我做了一些测试来验证它,我打算定义如下对象之间的关系。请复习一下 代码应该如下所示JavaScript原型链中的方法继承,javascript,javascript-objects,Javascript,Javascript Objects,“在javascript中,每个对象都有一个指向创建它的对象的秘密链接,形成一个链。当一个对象被要求提供一个它没有的属性时,它的父对象会被要求……不断地向上链,直到找到该属性或到达根对象。” 总之,我一直认为上面的话是事实,即使是现在,所以我做了一些测试来验证它,我打算定义如下对象之间的关系。请复习一下 代码应该如下所示 //Shape - superclass function Shape() { this.x = 0;
//Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
};
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
alert('Shape move');
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this); //call super constructor.
}
Rectangle.prototype.move = function(x, y) {
this.x += x;
this.y += y;
alert('Rectangle move');
};
// Square - subclass
function Square(){
Shape.call(this);
}
Rectangle.prototype = Object.create(Shape.prototype);
Square.prototype=Object.create(Rectangle.prototype);
var rect = new Rectangle();
var sq= new Square();
sq.x=1;
sq.y=1;
sq.move(1,1);
由于
move
方法无法在Square.prototype
中找到,因此JavaScript会在其链后面的父对象中找到它,我原以为它会在矩形.prototype
中找到,但实际上它是在根形状.prototype
中找到的,所以我不理解的是为什么sq.move(1,1)
实际上调用形状.原型.移动
而不是调用矩形.原型的移动
方法
?我遗漏了什么吗?谢谢。你刚刚覆盖了你的矩形.原型
已经有了移动
。既然你已经覆盖了它,你附加的移动
不再存在,这就是使用形状
移动的原因
Rectangle.prototype.move = function(x, y) {
this.x += x;
this.y += y;
alert('Rectangle move');
};
function Square(){
Shape.call(this);
}
//overwritten the prototype
Rectangle.prototype = Object.create(Shape.prototype);
在添加到原型对象之前,首先创建原型对象
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.move = function (x, y) {
this.x += x;
this.y += y;
alert('Rectangle move');
};
将原型的扩展向下移动。 现在,您正在扩展原型之后分配原型,因此它将覆盖扩展的原型
//Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this); //call super constructor.
}
// Square - subclass
function Square(){
Shape.call(this);
}
Rectangle.prototype = Object.create(Shape.prototype);
Square.prototype = Object.create(Rectangle.prototype);
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
alert('Shape move');
};
Rectangle.prototype.move = function(x, y) {
this.x += x;
this.y += y;
alert('Rectangle move');
};
var rect = new Rectangle();
var sq = new Square();
sq.x=1;
sq.y=1;
sq.move(1,1);
Square()
构造函数应该调用Rectangle()
而不是Shape()
?因为Square
是一个Shape
子类,而不是Rectangle
子类(?),让我试试,我想这不是问题。是不是Retangle.prototype=newshape()
使用Object.create()更容易
?@All,调用
方法只是调用构造函数
,它与原型
对象无关。顺便说一句,通常继承链总是关于对象的原型。构造函数
仅用于构造所创建的对象。这与提升无关;而代码只是简单地覆盖了矩形。原型
:)@Jack哦,是的。他的代码太复杂了,我一开始以为是这样。Thanks@JosephtheDreamer现在我知道原因了Object.create
将为矩形指定另一个实例。prototype
,因此在我的代码中,矩形中不再存在move
方法。prototype
,因为有另一个对象覆盖了前面的对象。希望你能证实我的理解。谢谢。覆盖-->覆盖很抱歉输入错误。