我是JavaScript的新手,目前正在学习课程。
我创建了一个简单的类,创建一个具有随机大小和颜色的正方形:
class Square {
constructor(maxSize = 150, minSize = 50) {
this.maxSize = maxSize;
this.minSize = minSize;
this.size = this.setRandomSize();
this.color = this.randomColor();
}
createShape() {
const square = document.createElement('div');
square.classList.add('square');
document.body.appendChild(square);
square.style.cssText = `
width: ${this.size}px;
height: ${this.size}px;
background-color: ${this.color};
`;
}
randomNumber(max, min = 0) {
return Math.floor(Math.random() * (max - min) + min);
}
setRandomSize() {
return this.randomNumber(this.maxSize, this.minSize);
}
randomColor() {
return `hsla(${this.randomNumber(360)}, 50%, 40%, .7)`;
}
}
new Square().createShape();正如您在上面的代码中所看到的,我有两个不使用任何实例或方法属性的方法randomNumber和setRandomColor。
我想知道在类内部或外部拥有这些函数(除了可移植性外)推荐的方法或好处(如下所示)。换句话说,是否建议将只与对象本质相关的类方法(代码块2)或允许类作为“独立”(代码块1)工作的方法保留在类内(代码块1)?。
class Square {
constructor(maxSize = 150, minSize = 50) {
this.maxSize = maxSize;
this.minSize = minSize;
this.size = this.setRandomSize();
this.color = randomColor();
}
createShape() {
const square = document.createElement('div');
square.classList.add('square');
document.body.appendChild(square);
square.style.cssText = `
width: ${this.size}px;
height: ${this.size}px;
background-color: ${this.color};
`;
}
setRandomSize() {
return randomNumber(this.maxSize, this.minSize);
}
}
function randomNumber(max, min = 0) {
return Math.floor(Math.random() * (max - min) + min);
}
function randomColor() {
return `hsla(${randomNumber(360)}, 50%, 40%, .7)`;
}
new Square().createShape();发布于 2021-10-24 12:07:31
当我开始学习编程的时候,我也有过类似的困惑。由于这是一堂课,我想在这里突出实心。
Single负责:类应该做一件事。你们班的工作是创造随机数吗?创建类是因为您想要一个正方形,而不是随机大小生成器。
另外,如果将函数放在类之外并在那里使用,那么类将与这些函数耦合。如果您需要使用rgb颜色而不是hsla,您将做什么?另一堂课?因此,减少耦合将提高您的课堂质量。
那我会怎么写这门课?
class Square {
constructor(size, color){
this.size = size;
this.color = color;
this.square = document.createElement('div');
this.square.classList.add('square');
document.body.appendChild(this.square);
this.square.style.cssText = `
width: ${this.size}px;
height: ${this.size}px;
background-color: ${this.color};
`;
}
}
function randomNumber(max, min = 0) {
return Math.floor(Math.random() * (max - min) + min);
}
function randomColor() {
return `hsla(${randomNumber(360)}, 50%, 40%, .7)`;
}
const size = randomNumber(100, 50)
const color = randomColor()
const mySquare = new Square(size, color)https://stackoverflow.com/questions/69696409
复制相似问题