[英]Javascript assigning object values to new object
So I am using options to pass values to a new object in a literal object fashion. 因此,我使用选项将值以文字对象形式传递给新对象。
var obj = new myObject({height:'500',width:'300');
function myObject(options){
}
I'm not sure the best route to get these values assigned to the object though so that this would work. 我不确定将这些值分配给对象的最佳途径,但这是否可行。
function myObject(options){
...assignment...
alert(this.width);
}
function myObject(options){
// copy the options into the current object
for (var key in options) {
if (options.hasOwnProperty(key)) {
this[key] = options[key];
}
}
alert(this.width); // 300
}
var obj = new myObject({height:'500',width:'300'});
You can even an extend this concept where you can have default property values myObject
, and you can override them with options
object: 您甚至可以扩展这个概念,使之具有默认属性值
myObject
,并且可以使用options
对象覆盖它们:
function myObject(options){
// DEFAULTS
this.name = 'Box';
this.width = '100';
this.height = '100';
// copy the options into the current object
for (var key in options) {
if (options.hasOwnProperty(key)) {
this[key] = options[key];
}
}
alert(this.width);
}
var obj = new myObject({height:'500',width:'300'}); // alert: 300
var obj2 = new myObject({height: '500'}); // alert: 100
var obj = new myObject({height:'500',width:'300'});
function myObject(options){
alert(options.width);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.