Kok*_*oko 6 javascript oop class ecmascript-6
在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(){
}
}
Run Code Online (Sandbox Code Playgroud)
但是在ES6中,你不能再在构造函数之外声明变量,这使得实际上更难以以OOP方式使用类!
您可以使用此方法在构造函数中声明变量,但这会使它们默认公开.这非常奇怪,因为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;
}
}
Run Code Online (Sandbox Code Playgroud)
ES6标准没有提供一种定义私有变量的新方法.
事实上,新的ES6 类只是围绕常规基于原型的构造函数的语法糖.
get和set关键字提供了一种简化ES5自定义getter和setter定义的方法,这些getter和setter之前使用Object.defineProperty()的描述符定义
下面的示例使用WeakMap存储私有属性.
// myModule.js
const first_name = new WeakMap();
class myClass {
constructor (firstName) {
first_name.set(this, firstName);
}
get name() {
return first_name.get(this);
}
}
export default myClass;
Run Code Online (Sandbox Code Playgroud)
我指的是David Vujic撰写的文章么?等待.真?不好了!(关于ES6课程和隐私的帖子)与使用WeakMaps的想法.
| 归档时间: |
|
| 查看次数: |
6779 次 |
| 最近记录: |