【发布时间】:2010-03-11 22:10:53
【问题描述】:
这是在 JavaScript 中描述“类”或构造函数的教科书标准方法,直接来自 JavaScript 权威指南:
function Rectangle(w,h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() {
return this.width * this.height;
};
我不喜欢这里的悬空原型操作,所以我试图想办法将area 的函数定义封装在构造函数中。我想出了这个,我确实不期望它会起作用:
function Rectangle(w,h) {
this.width = w;
this.height = h;
this.constructor.prototype.area = function() {
return this.width * this.height;
};
}
我没想到这会起作用,因为 area 函数内的 this 引用应该指向 area 函数本身,所以我无法访问 width 和 height this。但事实证明我愿意!
var rect = new Rectangle(2,3);
var area = rect.area(); // great scott! it is 6
一些进一步的测试证实,area 函数中的 this 引用实际上是对 正在构建的对象的引用,而不是 area 函数本身。
function Rectangle(w,h) {
this.width = w;
this.height = h;
var me = this;
this.constructor.prototype.whatever = function() {
if (this === me) { alert ('this is not what you think');}
};
}
原来警报弹出,this 正是正在构建的对象。那么这里发生了什么?为什么this 不是我期望的this?
【问题讨论】:
-
如果您有一百个矩形,您将重新声明该原型方法一百次。还好你只有一种方法……
标签: javascript prototypal-inheritance