访问器属性
普通写法
let course = {
lesson: {
name: 'ES6',
score: 60,
},
//读取接口
getScore() {
return {
name: this.lesson.name,
course: this.lesson.score,
}
},
//设置接口
setScore(score) {
//设置接口一般都要写验证
if (score >= 0 && score <= 100) {
this.lesson.score = score
} else {
console.log('成绩必须在1-100分之间')
}
},
}
console.log(course.lesson.name)
console.log(course.getScore())
course.setScore(80)
console.log(course.getScore())
console.log('-----------------------')
用户习惯
//console.log(course.score)
//course.score = 90
// ? 使用“访问器属性”就可以实现
course = {
lesson: {
name: 'ES6',
score: 60,
},
score: 99,
//getScore ===> get score
//普通方法 ===> 访问器属性
//如果使用访问器属性,get必须要有,set可选
get score() {
return {
name: this.lesson.name,
course: this.lesson.score,
}
},
//将一个方法,伪装成“属性”
set score(score) {
//设置接口一般都要写验证
if (score >= 0 && score <= 100) {
this.lesson.score = score
} else {
console.log('成绩必须在1-100分之间')
}
},
}
console.log(course.score)
course.score = 90
console.log(course.score)
访问器属性优先级大于同名属性
对象中有同名属性score,也有访问器属性get score和set score
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!