在一种计算面积的方法中,在定义变量时,我使用了这个,而在其他方法中(在计算周长时)我没有使用(如代码所示)。两个变量之间有什么区别(有和没有这个?)
function Rectangle(height, width) {
this.height = height;
this.width = width;
this.calcArea = function() {
this.areaRec = this.height * this.width; //here "this" is used for the variable areaRec to calculate & be returned
return this.areaRec;
};
this.calcPerimeter = function() {
perimeter = (2*(this.height + this.width)); //here without "this" the varible is caculated and returned; both returns correct result
return perimeter;
};
}
var rex = new Rectangle(7,3);
var area = rex.calcArea();
var perimeter = rex.calcPerimeter();
最佳答案
在 calcArea 中,除了返回计算结果之外,您还可以在 Rectangle 对象的 areaRec 属性上设置计算结果(使其可以在 Rectangle.areaRec 上访问)。在 calcPerimeter 中,您只是返回计算结果(请注意,calcPerimeter 未在函数中定义,因此它将成为 window 对象上的全局属性)。
关于javascript - 这个在JS中的用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32312766/