More
More

js:对象-属性-set/get

  |  

碎语

  js有对象-属性这早已耳熟能详,直到偶然看到某开源js源码才发现,同java一样,它也有对应的set/get方法

demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var che = {
_wheels: 4,
get wheels() {
return this._wheels;
},
set wheels(value) {
if(value < 1) {
console.log('give me a wheel at least,please!');
} else {
this._wheels = value;
}
}
};
console.log("che.wheels: "+che.wheels);
console.log("che._wheels: "+che._wheels);
che.wheels = 2;
console.log("che.wheels: "+che.wheels);
console.log("che._wheels: "+che._wheels);
che.wheels = 0;
console.log("che.wheels: "+che.wheels);
console.log("che._wheels: "+che._wheels);

兼容:这种写法并==不支持IE8==,替代方法如下;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var che2 = {
_wheels: 4
};
Object.defineProperty(che2, "wheels", {
get: function () {
return this._wheels;
},
set: function (value) {
if(value < 1) {
console.log('give me a wheel at least,please!');
} else {
this._wheels = value;
}
}
});

补充

传说中的标准写法(不代表常用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function Field(val){
this.value = val;
}
Field.prototype = {
get value(){
return this._value;
},
set value(val){
this._value = val;
}
};
var field = new Field("che");
console.log(field.value);
field.value = "che2";
console.log(field.value);

常用写法(外界无法修改默认值)

1
2
3
4
5
6
7
8
9
10
var che3 = {
get wheels() {
return 4;
}
};
console.log("che3.wheels: " + che3.wheels);
che3.wheels = 2;
console.log("che3.wheels: " + che3.wheels);

最后祝各位程序员,新年吉祥。早!日!脱!单

参考网络之美:JavaScript中Get和Set访问器的实现

打赏
手机扫一扫,支持CHE~