【发布时间】:2016-03-28 20:17:49
【问题描述】:
在 ES5 中,您可以模拟具有私有和公共变量的类,如下所示:
car.js
function Car() {
// using var causes speed to be only available inside Car (private)
var speed = 10;
// public variable - still accessible outside Car
this.model = "Batmobile";
// public method
this.init = function(){
}
}
但是在 ES6 中,您不能再在构造函数之外声明 var,这实际上使得以 OOP 方式处理类变得更加困难!?
您可以使用 this 在构造函数中声明变量,但默认情况下会公开它们。这很奇怪,因为 ES6 DOES 有一个 get / set 关键字!
class Vehicle {
constructor(make, year) {
// the underscore is nice, but these are still public!
this._make = make;
this._year = year;
}
// get and set can be handy, but would make more sense
// if _make and _year were not accessible any other way!
get make() {
return this._make;
}
get year() {
return this._year;
}
}
【问题讨论】:
-
this._make = make;与this.model = "Batmobile";的效果相同,你必须使用完全不同的技巧来定义私有变量,更多信息请参见What? Wait. Really? Oh no! (a post about ES6 classes and privacy)。 -
是的,但是 ES5 示例中的速度是私有的。如何在 ES6 中实现这一点?感谢您的链接!似乎 ES6 类在我们认为它们是真正的 OOP 类之前还有很长的路要走。
标签: javascript class oop ecmascript-6