所以我使用选项以文字对象的方式将值传递给新对象.
var obj = new myObject({height:'500',width:'300');
function myObject(options){
}
Run Code Online (Sandbox Code Playgroud)
我不确定将这些值分配给对象的最佳路径,以便这样做.
function myObject(options){
...assignment...
alert(this.width);
}
Run Code Online (Sandbox Code Playgroud)
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'});
Run Code Online (Sandbox Code Playgroud)
您甚至可以扩展此概念,您可以使用默认属性值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
Run Code Online (Sandbox Code Playgroud)