方法一:
let Girl = (function() {
var _weight = 0
function P(name, weight) {
this.name = name
_weight = weight
}
P.prototype.getWeight = function() {
return _weight
}
return P
})()
let girl = new Girl('zizi', 49)
console.log(girl)
console.log(girl.getWeight())
利用闭包特性,以及原型模式来实现。
方法二
let Girl = (function() {
var n = Symbol('weight')
function P(name, weight) {
this.name = name
this[n] = weight
}
P.prototype.getWeight = function() {
return this[n]
}
return P
})()
console.log(girl)
console.log(girl.getWeight())
利用symbol的特性,来生成一个受保护的key。从而实现属性私有化。