使用原型获得更高的性能

问题描述 投票:0回答:1

说我有100个从此构造函数继承相同属性的盒子:

const Box = function() {

    this.element = document.createElement("div");
    this.painted = false;

    this.init = function() {

        this.element.className = "box";

        this.element.addEventListener("mouseover", () => {
            console.log("you are touching this box!");
            this.change_color("red");
            this.painted = true;
        });
    }

    this.change_color = (color) => this.element.style.background = color;

}

现在,据我所知,我无法在.addEventListener中使用原型,因为每个盒子都需要其侦听器。但是函数this.change_color呢?每个盒子是否真的需要具有此功能?我可以用它做一个原型吗? (我猜不是因为它使用了框的元素,这是局部变量,对吗?)

或者,假设我要创建一个为页面中所有框上色的函数。您将如何制作原型呢?

javascript prototype
1个回答
0
投票

使用类和原型方法,您的代码将如下所示:

class Box {
  constructor() {
    this.element = document.createElement("div");
    this.painted = false;
  }
  init() {
    this.element.className = "box";
    this.element.addEventListener("mouseover", () => {
      console.log("you are touching this box!");
      this.change_color("red");
    });
  }
  change_color(color) {
    this.element.style.background = color;
  }
}

现在,initchange_colorBox.prototype上,而不是直接在每个实例上。

或者,假设我要创建一个为页面中所有框上色的函数。您将如何制作原型呢?

一个选项是将每个Box实例保存在构造函数中的数组中,然后对其进行迭代,例如:

const boxes = [];
// ...
constructor() {
  boxes.push(this);
}
// ...
boxes.forEach(box => box.change_color('green'));

[如果要在为所有框着色时调用了每个框的init,还可以附加一个样式标签,而无需迭代或数组:

document.body.appendChild(document.createElement('style')).textContent = `
  .box {
    background-color: green;
  }
`;

0
投票

prototype函数中,您可以简单地使用this,它将引用您创建的Box类的实际实例。因此,您可以为prototypeinit函数创建一个change_color,如下所示:

const Box = function(boxName) {
    this.element = document.createElement("div");
    this.painted = false;
    this.myname = boxName;
}

Box.prototype.init = function() {
  this.element.className = "box";
  this.element.innerText = this.myname;

  this.element.addEventListener("mouseover", () => {
    // console.log("you are touching this box!");
    this.change_color("red");
    this.painted = true;
  });
  
  this.element.addEventListener("mouseleave", () => {
    this.change_color("green");
    this.painted = true;
  });
}

Box.prototype.change_color = function(color) {
  this.element.style.background = color;
}

const box1 = new Box('box1');
box1.init();

const box2 = new Box('box2');
box2.init();

document.body.append(box1.element);
document.body.append(box2.element);
.box {
  height: 50px;
  width: 50px;
  border: 1px solid blue;
}
© www.soinside.com 2019 - 2024. All rights reserved.