gpt4 book ai didi

javascript - 如何在 JavaScript 中动态设置对象的属性

转载 作者:行者123 更新时间:2023-11-30 14:51:28 27 4
gpt4 key购买 nike

所以我有一个 JS 对象,看起来像..

var Monitor=function(parent,params={}){
this.parent=null;
this.canvas=null;
this.width=600;
this.height=400;
this.backColor="#252525";
this.lineColor="#0171a7";
this.lineWidth=4;
this.radius=3;

/* 2017-12-31 **********************************
Innitialize the monitor class
***********************************************/
this.init=function(parent,params){
var that=this;
this.parent=parent;

//Loop through params and set them.
$.each(params,function(i,val){
eval("that."+i+"="+val);
})
return this;
};

this.init(parent,params);
}

并用...调用它

mc=new Monitor(
$("#monitors"),
{
"width":800;
"height":600,
}
);

我想在循环中动态设置属性。

但是,要让它工作,我必须使用 eval(Eval 是邪恶的……对吧?)。那么有没有更好的方法来动态设置属性?

最佳答案

就这样吧:

 that[i]=val;

这里是完整的工作示例:

var Monitor=function(parent,params={}){
this.parent=null;
this.canvas=null;
this.width=600;
this.height=400;
this.backColor="#252525";
this.lineColor="#0171a7";
this.lineWidth=4;
this.radius=3;

/* 2017-12-31 **********************************
Innitialize the monitor class
***********************************************/
this.init=function(parent,params){
var that=this;
this.parent=parent;

//Loop through params and set them.
$.each(params,function(i,val){
// eval("that."+i+"="+val);
that[i]=val;
})
return this;
};

this.init(parent,params);
}


mc=new Monitor(
$("#monitors"),
{
"width":800,
"height":600
}
);
debugger;
console.dir(mc.height);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 如何在 JavaScript 中动态设置对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48044941/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com