说我有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
呢?每个盒子是否真的需要具有此功能?我可以用它做一个原型吗? (我猜不是因为它使用了框的元素,这是局部变量,对吗?)
或者,假设我要创建一个为页面中所有框上色的函数。您将如何制作原型呢?
使用类和原型方法,您的代码将如下所示:
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;
}
}
现在,init
和change_color
在Box.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;
}
`;
在prototype
函数中,您可以简单地使用this
,它将引用您创建的Box类的实际实例。因此,您可以为prototype
和init
函数创建一个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;
}