如何在 JavaScript 中创建对象构造函数;

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)

Maj*_*awi 4

您需要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)

  • 如果您从“box”返回 DOM 元素,那么使用“new”并向“new box”创建的对象添加属性是没有意义的。没有什么可以保留创建的对象“new box”...... (2认同)