Bir*_*man 5 javascript class function
我试图弄清楚在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();
Run Code Online (Sandbox Code Playgroud)
输出:
Joe
TestClass
Run Code Online (Sandbox Code Playgroud)
到目前为止,通过此处的测试,我真正能看到的唯一区别是,我无法this.name在我的getName2中访问,因为我认为它与TestClass的任何实例都没有关联。所以我的getName2几乎就像一个静态类函数,它不与该类的实例关联?请帮助我阐明这一点,以及为什么我会选择以一种方式而不是另一种方式实现功能。
Bri*_*ams 16
来自MDN 文档:
ECMAScript 2015 中引入的 JavaScript 类主要是对 JavaScript 现有的基于原型的继承的语法糖。类语法没有向 JavaScript 引入新的面向对象的继承模型。
所以这...
class TestClass {
constructor(myName) {
this.name = myName;
}
getName() {
return this.name;
}
static getName2() {
return 'getName2 result';
}
}
Run Code Online (Sandbox Code Playgroud)
...完全等同于:
const TestClass = function(myName) {
this.name = myName;
}
TestClass.prototype.getName = function() {
return this.name;
}
TestClass.getName2 = function() {
return 'getName2 result';
}
Run Code Online (Sandbox Code Playgroud)
因此,您使用旧的原型语法还是新的 ES6class语法只是个人喜好的问题,正如您所怀疑的那样,直接在 a 上定义方法class完全等同于创建一个static类 method。