setter&getter

Posted qjb2404

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了setter&getter相关的知识,希望对你有一定的参考价值。

let _age = 4

class Animal {

   construct (type){

      this.type = type

   }

   get age(){

      return _age

   }

   set age(val){

      if(val < 7 && val >4){

         _age = val

     }

   }

   eat(){

      console.log(‘eat food‘)

   }

}

let dog = new Animal(‘dog‘)

console.log(dog.age)

dog.age = 6

console.log(dog.age)

console.log(dog._age)

以上是关于setter&getter的主要内容,如果未能解决你的问题,请参考以下文章