我正在尝试理解JavaScript中的“类”。
通常在JavaScript中模拟类看起来像这样:
function MyClass(someParameter) {
this.someValue = someParameter;
this.someOtherValue = "green";
}
MyClass.prototype.someMethod = function() {
console.log("Hello!");
};
虽然在构造函数中设置了非函数成员,但是将该方法添加到构造函数之外的构造函数的.prototype
属性中。
我想了解原因。为什么不在构造函数内部创建方法,就像其他成员一样?含义:
function MyClass(someParameter) {
this.someValue = someParameter;
this.someOtherValue = "green";
this.someMethod = function() {
console.log("Hello!");
}
}
答案 0 :(得分:1)
以下是一些要点:
答案 1 :(得分:1)
为什么不在构造函数中创建方法,就像其他成员一样?
因为实例之间的方法通常不同。在您的示例中,每个实例都具有相同的 someMethod
方法,执行完全相同的操作。因此,只有一次创建该方法才有意义。
另一方面,标量数据通常是特定的到实例(即实例之间不同),因此应该在构造函数中初始化。
FWIW,ECMAScript6引入了新的class
语法,鼓励这种结构。
function MyClass(someParameter) {
this.someValue = someParameter;
this.someOtherValue = "green";
}
MyClass.prototype.someMethod = function() {
console.log("Hello!");
};
相当于
class MyClass {
constructor(someParameter) {
this.someValue = someParameter;
this.someOtherValue = "green";
}
someMethod() {
console.log("Hello!");
}
}