1、getter 和 setter
1、set 有且仅有一个参数
2、get不允许有任何参数
var obj = {
a:1,
_c:0,
b:function(){},
//set有且仅有一个参数
set c(value){
document.documentElement.style.backgroundColor = "#" + value.toString(16);
this._c=value;
},
//不允许有任何参数
get c(){
return this._c;
}
}
setInterval(function(){
obj.c++
},16)
如果仅有set,没有get,这个属性就是只写属性
如果仅有get,没有set,这个属性就是一个只读属性
下面是运用get和set的基本属性的重构与赋值的案例,最后设置height、width和bgcolor的自变化
var div = document.querySelector("div");
Object.defineProperties("div",{
_width:{
writable:true,
value:0,
},
_height:{
writable:true,
value:0,
},
_bgColor:{
writable:true,
value:0,
},
width:{
enumerable:true,
set:function(_value){
this.style.width = _value.toString().indexOf("px")>-1 ? _value : _value + "px";
this._width=_value;
},
get:function(){
return this._width;
}
},
height:{
enumerable:true,
set:function(_value){
this.style.height = _value.toString().indexOf("px")>-1 ? _value : _value + "px";
this._height=_value;
},
get:function(){
return this._height;
}
},
width:{
enumerable:true,
set:function(_value){
this.style.backgroundColor = typeof _value === "string" ? _value : #"+_value.toString(16).padStart(6,"0");
this._bgColor = _value;
},
get:function(){
return this._bgColor;
}
},
})
setInterval(function(){
div.width++;
div.height++;
div.bgColor++;
},100)
下面是运用set和get做的一个案例:两秒创建一个红色圆形,并将其文本内容设置为自身的序号。
import Utils from "./js/Utils.js";//外部引入js里面的ce(自己封装)方法,主要是为了创建标签并设置样式属性
var div=document.querySelector("div");
var obj={
_arr:[];//临时数组
set arr(value){
if(!Array.isArray(value)) return;//判断是否为数组,若不是数组则返回
if(this._arr.join()===value.join());//判断数组是否改变若不改变则返回
div.innerHTML="";//将div中的内容清空
for(var i=0;i<value.length;i++){
let ball=Utils.ce("div",{
width:"50px",
height:"50px",
backgroundColor:"red",
color:"#FFFFFF",
textAlign:"center",
lineHeight:"50px",
borderRadius:"50px",
float:"left"
},div);
ball.textContent=value[i];
}
this._arr=value;
},
get arr(){
return this._arr;
}
}
var a=[];
var t=0;
setInterval(animation,2000);
function animation(){
t++;
a.push(t);
obj.arr=a.slice();//改变a的引用地址,使其与arr的引用地址不一样,以便于 if(this._arr.join()===value.join());判断完成
}
效果图

本文探讨了JavaScript中使用getter和setter方法封装属性的过程,通过实例展示了如何利用这些方法实现元素宽度、高度及背景色的动态变化,以及如何创建动态更新的圆形元素。

1万+

被折叠的 条评论
为什么被折叠?



