Javascript ';这';在调用函数时,将其用于具有超类的子类
当调用函数中的“this”一词用在超类的子类中时,我很难理解它:Javascript ';这';在调用函数时,将其用于具有超类的子类,javascript,Javascript,当调用函数中的“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,
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
在PositionedRectangle类中。“this”代表什么?我可以用什么替换它,使代码可以正常工作?
我认为第一个“this”和Rectangle是一样的,我试着用名称Rectangle来代替它,但它不起作用。我认为它是一个PositionedRectangle子类,我试着用PositionedRectangle替换它
我读到“this”的意思取决于调用它的方式,我知道call函数中的第一个参数表示一个对象,但当该对象的值为“this”时,我不理解它实际表示什么
正如你所看到的,我对JavaScript还是新手
我感谢你的帮助 是一个javascript函数,它调用或仅运行具有给定上下文和参数的函数
Q:在定位角度类中。“this”代表什么
A:它代表函数的构造函数positionedlectangle
Q:我可以用什么替换它,使代码可以正常工作
A:对我来说,这只是一些非结构化的功能,让人相当困惑
Q:我认为第一个“this”与矩形相同
A:javascript中没有子类/超类,this
在矩形行中。调用(this,w,h)代码>指的是定位角度的上下文您可以阅读有关上下文和此的更多信息
Q:…但当该对象的值为“this”时,我不明白它实际上代表什么
A:让我给你举个例子,让你更容易理解。想象一下,我重复一下,想象一下你有两个函数a
和b
。a的上下文指的是c
,b的上下文指的是d
function a(){
this; //refers to c
}
function b(){
this; //refers to d
}
现在,如果在a的上下文中调用a
函数中的b
,如下所示:
function a(){
b.call(this); //remember this refers to c in a function
}
您正在将b
的上下文从d
更改为c
,因此如果您返回b
的上下文:
function b(){
return this;
}
再回到整个画面,你会看到不同之处:
function a(){
this; //refers to c
this.bContext=b.call(this);
}
function b(){
return this; //refers to d
}
b(); //returns d
a.bContext; //returns c
我知道一开始有点混乱,但是你会慢慢理解的,所以不要太用力。第一个参数this
表示在你调用的函数Rectangle
中使用时,this
的值。停止思考“子类”和“超类”的可能重复。Javascript没有基于类的继承,句号。我肯定需要更多的时间来完全理解这一点。我将阅读更多内容,并尝试找到其他一些示例。多亏了你的帖子和之前的评论,我想我已经了解了一点。谢谢
function a(){
this; //refers to c
this.bContext=b.call(this);
}
function b(){
return this; //refers to d
}
b(); //returns d
a.bContext; //returns c