gpt4 book ai didi

javascript - 当子类与父类(super class)一起使用时,调用函数中的“this”

转载 作者:行者123 更新时间:2023-11-27 22:35:03 24 4
gpt4 key购买 nike

当调用函数中的“this”这个词在具有父类(super class)的子类中使用时,我在理解它时遇到了一些困难,如下所示:

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”与“矩形”相同,我尝试将其替换为名称“矩形”,但它不起作用。我认为它是一个 PositionedRectangle 子类,我尝试用 PositionedRectangle 替换它。

我读到“this”的含义取决于它的调用方式,并且我知道调用函数中的第一个参数代表一个对象,但是当该对象的值是“this”时,我不明白它实际代表什么。

如您所见,我对 JavaScript 还很陌生。

感谢您的帮助。

最佳答案

<强> call 是 javascript 函数,它使用给定的上下文和参数调用或简单地运行函数。

Q: in PositionedRectangle class. What 'this' stands for?

A:它代表函数PositionedRectangle的构造函数。

Q: With what can I replace it so the code can work normally?

答:您想要实现的目标相当令人困惑,因为对我来说这似乎只是一些非结构化函数!

Q: I thought first 'this' is same as Rectangle...

答: javascript 中没有子类/父类(super class),this在线Rectangle.call(this, w, h);指的是 PositionedRectangle 的上下文,您可以阅读有关 contextthis 的更多信息 here .

Q: ...but when the value of that object is 'this' I don't understand what that actually represents.

答:我给你举个例子,方便你理解。想象一下,我重复一遍想象你有两个函数 ab 。 a 的上下文指的是 c b 的上下文引用 d

function a(){
this; //refers to c
}
function b(){
this; //refers to d
}

现在如果您调用ba函数与 a 的上下文如下:

function a(){
b.call(this); //remember this refers to c in a function
}

您正在更改 b 的上下文来自dc ,所以如果您返回 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

我知道一开始有点令人困惑,但随着时间的推移你会明白的,所以不要逼得太紧。

关于javascript - 当子类与父类(super class)一起使用时,调用函数中的“this”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39188945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com