【发布时间】:2016-08-28 07:27:36
【问题描述】:
当调用函数中的“this”这个词用在超类的子类中时,我很难理解这个词:
function Rectangle(w, h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() { return this.width * this.height; }
function PositionedRectangle(x, y, w, h) {
Rectangle.call(this, w, h);
this.x = x;
this.y = y;
}
PositionedRectangle.prototype = new Rectangle();
delete PositionedRectangle.prototype.width;
delete PositionedRectangle.prototype.height;
PositionedRectangle.prototype.constructor = PositionedRectangle;
PositionedRectangle.prototype.contains = function(x, y) {
return (x > this.x && x < this.x + this.width &&
y > this.y && this.y + this.height);
}
var r = new PositionedRectangle(2, 2, 2, 2);
document.write(r.contains(3, 3)); // 4
document.write("<br>" + r.area()); // 4
document.write("<br>" + r.x + ", " + r.y + ", " + r.width + ", " + r.height + "<br>"); // 2, 2, 2, 2
document.write(r instanceof PositionedRectangle && r instanceof Rectangle && r instanceof Object); // true
现在这部分我不明白:
Rectangle.call(this, w, h);
在 PositionedRectangle 类中。 “这”代表什么?我可以用什么替换它以便代码可以正常工作? 我首先认为“this”与 Rectangle 相同,我试图用名称 Rectangle 替换它,但它没有用。比我认为它是一个 PositionedRectangle 子类我试图用 PositionedRectangle 替换它。
我读到“this”的含义取决于它的调用方式,并且我知道调用函数中的第一个参数代表一个对象,但是当该对象的值为“this”时,我不明白它实际代表什么。
如你所见,我还是 JavaScript 新手。
感谢您的帮助。
【问题讨论】:
-
第一个参数
this表示在您正在调用的函数Rectangle中使用时this的值。 -
停止思考“子类”和“超类”。 Javascript 没有基于类的继承,句号。
标签: javascript