【问题标题】:What is difference between function within class constructor function and the method Inside class but outside constructor function (in js)?类构造函数内的函数与类内但构造函数外的方法(在js中)有什么区别?
【发布时间】:2021-01-08 17:27:42
【问题描述】:

类构造函数内的函数与类内构造函数外的方法(在js中)有什么区别?

我试图对此进行搜索,但没有找到我可以理解的内容!

提前致谢!

  class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;

    /* this function within the constructor what is it’s difference
      from the method(1) below */

    withinFunction = function () { console.log(“This is rectangle”)};
  }
  
  // Method(1)
  calcArea() {
    return this.height * this.width;
  }
}

【问题讨论】:

  • “我试图搜索这个,但没有找到我可以理解的东西!” ...我怀疑...MDN :: Class body and method definitions
  • 因为你的代码没有声明withinFunction,所以创建了一个全局变量。如果用letconst 声明,它将是构造函数中的局部符号,根本不会影响构造的对象。

标签: javascript class methods constructor


【解决方案1】:

在那个特定示例中,代码正在成为我所说的The Horror of Implicit Globals 的牺牲品。 withinFunction 是一个全局变量(除非它声明在你没有显示的地方)。

比较正常的版本是这样的:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;

    this.withinFunction = function () { console.log(“This is rectangle”)};
//  ^^^^^
  }
  
  // Method(1)
  calcArea() {
    return this.height * this.width;
  }
}

不同之处在于每次调用构造函数时都会创建withinFunction,并将其分配为正在创建的对象上的“自己的”属性。相反,calcArea(使用方法语法定义)在评估class 构造并放置在分配为创建对象原型的对象上时创建一次通过构造函数 (Rectangle.prototype)。所以只有一个calcArea 的副本被所有实例共享,但withinFunction 是为每个实例单独创建的。

它们都有各自的用途,尤其是当 withinFunction 是使用箭头函数语法而不是传统的函数语法创建时。

如果你使用class 语法,一般来说,共享方面最好使用方法语法(尽管现代 JavaScript 引擎在让多个函数对象共享相同代码方面非常有效)并且因为它更容易模拟原型用于测试的函数。

【讨论】:

    猜你喜欢
    • 2011-04-16
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 2022-10-15
    相关资源
    最近更新 更多