Javascript 对象。从对象创建
总之,如果我将一个对象传递到Javascript 对象。从对象创建,javascript,Javascript,总之,如果我将一个对象传递到对象.create,这意味着创建一个新对象继承自它。下面的代码证明了这一点 function Shape() { this.x = 0; this.y = 0; } Shape.prototype.move = function(x, y) { this.x += x; this.y += y; consol
对象.create
,这意味着创建一个新对象继承自它。下面的代码证明了这一点
function Shape() {
this.x = 0;
this.y = 0;
}
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info("Shape moved.");
};
Rectangle = Object.create(Shape);
Rectangle.__proto__==Shape;//it is true.yes, I can understand
Rectangle//It is Function {} I can not understand it.
Rectangle.constructor==Function//it is true.I can not understand it.
下图显示了这种关系。但我不能理解的是它的突出部分。矩形到底是什么?我的意思是什么是函数{}
,它来自哪里?还有Rectangle.constructor
属性,我不知道所有对象是否都有constructor
属性,以及constructor
属性的用途是什么?谢谢
PS:以上所有数值都是在FireBug中计算和观察的
根据minitech的评论更正图表
这就是使用Object.create进行继承的方式。它应该是这样的:
function Shape() {
this.x = 0;
this.y = 0;
}
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info("Shape moved.");
};
function Rectangle() {
Shape.call(this);
}
Rectangle.prototype = Object.create(Shape.prototype); // Leaving out the constructor business for simplicity
你在那里做的是复制实际的形状
函数,所以当然(作为一个函数)它的构造函数是函数
请注意,矩形。uuu proto_uuu=Shape
不是一个比较。+1-+2当您添加一些有关构造函数及其功能的信息时;-)@西恩维拉:哪个构造器<代码>函数
或矩形
或“排序矩形
”?:DHi,所有人,很抱歉错过了另一个=
,应该是“==”,请再次查看。谢谢。它应该是矩形。\uuuuu proto\uuuuu==Shape
嗨,所有,在我的测试代码中,我只想创建从Shape
继承的对象,而不是Shape.prototype
,并尝试弄清楚如果这样做会发生什么。谢谢