JavaScript get set方法 ES5/ES6写法

网上鲜有get和set的方法的实例,在这边再mark一下。this

get和set我我的理解自己只是一个语法糖,它定义的属性至关于“存储器属性”spa

为内部属性提供了一个方便习惯的读/写方式prototype

ES5写法

 1 function Number(num) {
 2   this._num = num           //这里的_num和get/set方法num()不能重名
 3 }
 4 
 5 //get/set方法使用同一个命名,增长可读性
 6 Number.prototype = {
 7   get num() {
 8     return this._num;
 9   },
10   
11   set num(num) {
12         this._num = num;
13   }
14 }
15 
16 var test = new Number(8);
17 console.log(test.num);
18 test.num = 88;
19 console.log(test.num);

输出:code

>8blog

>88get

 

在这里,定义了Number类的一个值_num,再原型中注入set和get方法,此时就可使用test.num取值和赋值,更加直观。原型

ES6写法

再看看用ES6中class的实现:io

 1 class Num {
 2   constructor(num) {
 3         this._num = num;
 4   }
 5   
 6   get num() {
 7     return this._num;
 8   }
 9   
10   set num(num) {
11     this._num = num;
12   }
13   
14 }
15 
16 var test = new Num(9);
17 console.log(test.num);
18 test.num = 99;
19 console.log(test.num);

 

输出:console

>9function

>99

相关文章
相关标签/搜索