day18_setter和getter
1.什么是setter和getter
-
setter
setter是一种设置属性值的方法 。
setter则负责设置键值,值是以参数的形式传递,在他的函数体中,一切的return都是无效的 。
-
getter
getter 是一种获得属性值的方法 。
getter负责查询值,它不带任何参数 。
对象的属性又可分为对象属性和访问器属性 。
get/set访问器称为访问器属性,不是对象的属性,而是属性的特性,特性只有内部才用。
-
set和get一般成对出现
如果只有set,没有get,只写不可读。
var obj = { _num : 1, set num(value){ this._num = value; } } console.log(obj.num);//undefined
如果没有set,只有get,表示该属性只读不可写。
var obj = { _num : 1, get num(){ return this._num; } } obj.num = 3; console.log(obj); //{_num: 1}
-
看个例子吧
var obj = {
_num: 0,
// set方法有且仅有一个参数,不使用return返回内容
set num(value) {
this._num = value;
},
// get方法不能有参数,并且必须使用return返回值
get num() {
return this._num;
}
}
// obj.num();//没有这个方法
//此时会调用set方法,将10传递到value中,并存储到this._num属性上
obj.num = 10;
//当num作为一种运算值使用时,调用get方法,取出this._num
console.log(obj.num);//10
注:num 没有存储值,存储在this._num;
-
数据驱动显示Demo
var obj = { n: 10, pre: null, list: [], _num: 0, init: function () { for (let i = 0; i < this.n; i++) { let div = document.createElement("div"); div.style.width = "50px"; div.style.height = "50px"; div.style.border = "1px solid #000000"; this.list.push(div); document.body.appendChild(div); } }, set num(value) { if (value > this.list.length - 1) value = 0; this._num = value; if (this.pre) { this.pre.style.backgroundColor = "white"; } this.pre = this.list[value]; this.pre.style.backgroundColor = "red"; }, get num() { return this._num; } } var speed = 0; var time = speed; obj.init(); //count为移动的次数,也就是最终停下的位置 var count = Math.floor(Math.random() * 20 + 20); setInterval(animation, 16); function animation() { time-=2; if (time > 0) return; speed++; time = speed; if (speed > count) return; obj.num++; }
-
set会防止二次设置
如果set的是一个对象值时,只有对象的引用地址发生改变时或者对象本身重新赋值,才执行set函数。
如果仅仅改变该对象的属性时,不会触发set函数。
var obj = { n: 10, pre: null, list: [], _style: {}, init: function () { for (let i = 0; i < this.n; i++) { let div = document.createElement("div"); div.style.width = "50px"; div.style.height = "50px"; div.style.border = "1px solid #000000"; this.list.push(div); document.body.appendChild(div); } }, set style(value) { // if(this._style===value) return; this._style = value; for (var i = 0; i < this.list.length; i++) { Object.assign(this.list[i].style, value); } }, get style() { return this._style; } } obj.init(); var bn = document.querySelector("button"); bn.addEventListener("click", clickHandler); function clickHandler(e) { obj.style.backgroundColor = "red"; obj.style = obj.style; //此处将对象重新赋值 }
-
面试题
使以下语句为true
(obj.a === 1 && obj.a === 2 && obj.a === 3)
- 方法一
var n = 1; var obj = { a:n; } Object.defineProperty(obj, "a", { get: function() { return n++; } }) console.log(obj.a === 1 && obj.a === 2 && obj.a === 3);
- 方法二
{ $data: { a: 1 } } Object.defineProperty(obj, "a", { get: function () { return this.$data.a++; } }) console.log(obj.a === 1 && obj.a === 2 && obj.a === 3);
网友评论