【发布时间】: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,所以创建了一个全局变量。如果用let或const声明,它将是构造函数中的局部符号,根本不会影响构造的对象。
标签: javascript class methods constructor