在一种计算面积的方法中,在定义变量时,我使用了这个,而在另一个方法中(在计算周长时)我没有使用(如代码所示)。两个变量之间的区别是什么(有和没有这种区别?)
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();发布于 2015-08-31 13:47:09
在calcArea中,除了返回计算结果外,还将设置矩形对象的areaRec属性的计算结果(使其在Rectangle.areaRec上可访问)。在calcPerimeter中,您只是返回计算结果(注意,函数中没有定义calcPerimeter,因此它将成为窗口对象上的一个全局属性)。
发布于 2015-08-31 13:47:43
这是一个不同的范围。您在perimeter函数之外声明了height,而没有在任何地方声明height或width,而且它们表面上是在Rectangle中动态声明自己。
在console.log(height);函数之外尝试Rectangle(),您应该在控制台中得到“未定义”。
如果移除perimeter =、return perimeter并将行var perimeter = rex.calcPerimeter()更改为两行:
var perimeter; rex.calcPerimeter();
那么console.log(perimeter);之后,您仍然应该得到要返回的值,因为perimeter的作用域是全局的。
发布于 2015-08-31 13:55:41
当使用this.areaRec =时,您将向this引用的对象添加一个新字段。调用smth.calcArea()之后,您将能够从其他任何地方读取smth.areaRec。
当使用perimeter =时,您将在window上创建这样的属性。因此,在调用smth.calcPerimeter()之后,您可以从其他任何地方读取window.perimeter或名为perimeter的全局变量。
正确的方法是像var perimeter =一样声明变量。在这种情况下,变量不会从函数中泄漏,而只是一个局部变量。
https://stackoverflow.com/questions/32312766
复制相似问题