这是描述 JavaScript 中“类”或构造函数的教科书标准方法,直接来自 JavaScript 权威指南:
function Rectangle(w,h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() {
return this.width * this.height;
};
我不喜欢这里的悬空原型(prototype)操作,所以我试图想办法将 area
的函数定义封装在构造函数中。我想到了这个,但我不期望它能工作:
function Rectangle(w,h) {
this.width = w;
this.height = h;
this.constructor.prototype.area = function() {
return this.width * this.height;
};
}
我没想到这会起作用,因为 area
函数中的 this
引用应该指向 area
函数本身,所以我无法从 this
访问 width
和 height
。但事实证明我知道!
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
?
最佳答案
我认为正确的答案是你不应该这样做,因为正如 kennebec 在评论中所说:
If you have a hundred rectangles, you are going to redeclare that prototype method a hundred times.
关于javascript - 从构造函数中将方法附加到原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2429059/