Ale*_*scu 5 javascript object-construction
您能解释一下下面的代码有什么问题吗?
function box (width, height, color) {
this.width=width;
this.height=height;
this.color=color;
this.style.width=width;
this.style.height=height;
this.style.backgroundColor=color;
}
var box1 = new box (100, 100, 'red');
document.body.appendChild(box1);
Run Code Online (Sandbox Code Playgroud)
您需要createElement向其传递参数,如下所示:
function box (width, height, color) {
this.element = document.createElement('div');
this.element.style.width=width+'px';
this.element.style.height=height+'px';
this.element.style.backgroundColor=color;
return this.element;
}
var box1 = box (100, 100, 'red');
document.body.appendChild(box1);Run Code Online (Sandbox Code Playgroud)