我想弄清楚在 JavaScript 的类内部或外部定义函数时是否有任何不同。 为什么我会选择一种方式而不是另一种方式?(注意我的 getName [inside class] 和 getName2 [outside of class])。
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 几乎就像一个静态类函数,它不与类的实例相关联?请帮助我澄清这一点,以及为什么我会选择以一种方式而不是另一种方式来实现功能。
最佳答案
来自MDN doc :
JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.
所以这个...
class TestClass {
constructor(myName) {
this.name = myName;
}
getName() {
return this.name;
}
static getName2() {
return 'getName2 result';
}
}
...完全等同于此:
const TestClass = function(myName) {
this.name = myName;
}
TestClass.prototype.getName = function() {
return this.name;
}
TestClass.getName2 = function() {
return 'getName2 result';
}
因此,无论您使用较旧的原型(prototype)语法还是较新的 ES6 class
语法都只是个人喜好问题,正如您所怀疑的那样,直接在 class
上定义方法完全等同于创建一个 static
class method .
关于javascript - 在类内和类外定义 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55204088/