定义一个人物类
- 假设其属性有姓名和性别
- 我们希望,性别在声明后就固定不变
- 传统方法
var Person = (function(){var _gender = '';function P(name, gender){this.name = name;_gender = gender;}P.prototype.getGender = function(){return _gender;}return P;
})();var p1 = new Person('栗子','男');
console.log(p1.getGender());
-
此时属性被私有保护起来了.
-
使用Symbol
var Person = (function(){let _gender = Symbol('gender');function P(name, gender){this.name = name;this[_gender] = gender;}return P})();var p1 = new Person('栗子','男');
console.log(p1[Symbol('gender')]);
- 外面只能看到,访问不到