1 回答
TA贡献1840条经验 获得超5个赞
userGear代码中显示的 getter 和 setter只是为了向您展示如何carProps在类内部的(私有)和外部作用域之间进行通信。该示例的重点是表明carProps无法访问该变量,除非通过故意公开的userGear方法。如果这些方法不存在,那么在构造函数中设置 WeakMap 之后,外部使用者Car将无法看到或使用它做任何事情,例如:
const Car = (function() {
const carProps = new WeakMap();
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
this._userGears = ["P", "N", "R", "D"];
carProps.set(this, { userGear: this._userGears[0] });
}
shift(gear) {
this.userGear = gear;
}
}
return Car;
})();
const car = new Car('foo', 'bar');
// at this point, at this level of scope,
// there is no way for a user of "car" or "Car" to reference carProps
console.log(car.userGear);
再举一个更有意义的例子,假设构造函数选择了一个类的用户必须猜测的随机数:
const Game = (function() {
const gameProps = new WeakMap();
return class Game {
constructor() {
gameProps.set(this, { randomNum: Math.floor(Math.random() * 10) });
}
guess(num) {
return gameProps.get(this).randomNum === num ? 'Win' : 'Lose';
}
}
})();
const game = new Game();
// at this point, at this level of scope,
// there is no way for a user of "Game" or "game" to reference gameProps
// or to figure out the random number, without guessing multiple times
console.log(
game.guess(1),
game.guess(2),
game.guess(3),
game.guess(4),
game.guess(5)
);
有了上面的代码,调用者没有办法在Game不调用(故意暴露的方法).guess几次的情况下找出游戏的内部随机数。(除非Math.random事先得到猴子补丁......)
添加回答
举报