javascript - 这个在JS中的用法?

标签 javascript oop methods this

在一种计算面积的方法中,在定义变量时,我使用了这个,而在其他方法中(在计算周长时)我没有使用(如代码所示)。两个变量之间有什么区别(有和没有这个?)

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/

相关文章:

javascript - 追加获取的 ejs 项目

php - 在 PHP 中调用 super 方法

php - 避免在 mysql 查询中进行硬编码

javascript - 在javascript中的另一个方法中调用方法?

coding-style - 如何命名类似工厂的方法?

javascript - 使用 2 个参数调用 onclick 函数

javascript - 有人如何能够发送此消息? (邮件过滤问题)

java - 将静态方法放在接口(interface)中是一种好习惯吗?

javascript - 如何检查我的 localStorage 中是否有特定值?

python - 如何从基类引用 Python 派生类的 __init__ 方法?