我正在尝试弄清楚在JavaScript中在类内部或外部定义函数是否有任何区别。为什么我会选择一种方式而不是另一种方式?(请注意我的getName [在类内部]和getName2 [在类外部])。
class TestClass {
constructor(myName) {
this.name = myName;
}
getName() {
return this.name;
}
}
TestClass.getName2 = function() {
//won't actually print the name variable set since not associated with an instance of the class?
console.log(this.name);
};
var test = new TestClass("Joe");
console.log(test.getName());
///////////////
TestClass.getName2();
输出:
Joe
TestClass
我在测试中所看到的唯一区别是,我无法在我的getName2中访问this.name,因为我认为它与TestClass的任何实例都没有关联。因此,我的getName2几乎就像一个静态类函数,它与类的实例无关。请帮助我澄清这一点,并解释为什么我会选择以一种方式实现函数而不是另一种方式。
getName2 =
在其所在的作用域中创建一个变量。TestClass.getName2 =
创建一个由TestClass
限定的变量。尽可能地,将变量限制在适当的上下文中是很好的。这可以最小化"命名空间污染"。并且表明getName2
可能正在访问或设置与TestClass有关但不是单个TestClass实例的值。也许是应该影响所有TestClass实例的"配置设置"。 - ToolmakerSteve