模拟get set

function fun() {
let pro;
this.get = () =>{

//XXXX

return pro
}
this.set = (value)=> {

//xxxx

pro = value
}
}

let f=new fun()
f.set(10)
console.log(f.get())

es5 字面量 get set

let student={
name:'li',
get prop(){
return this.name
},
set prop(value){
this.name=value
}
}

console.log(student.prop)
student.prop='liu'
console.log(student.prop)

es6 class get set

class Student{
constructor(name){
this.name=name
}
get prop(){
return this.name
}
set prop(value){
this.name=value
}
}

let student=new Student('li')

console.log(student.prop)
student.prop='liu'
console.log(student.prop)

上面的两种方式的属性时公开的,如果想要属性私有化,使用Object.defineProperty

function student(name){
let _name=name

Object.defineProperty(this,'prop',{
get:()=>{
return _name
},
set:value=>{
_name=value
}
})
}