0

我有这个用 OOP 编写的简单代码块。我想操纵这句话,以便将最后一个参数 ( faveColor) 更改为指定的实际颜色。我知道我需要编写某种函数来做到这一点,但我不知道怎么做。

我真的很困惑如何以最干净的方式解决这个问题。基本上这样句子就会输出“你好,我的名字是 John Doe,我最喜欢的颜色是 ${red/orange/blue/green} 等。每个选项的颜色都会变化。

 function Person(fullName, faveColour) {
      this.name = fullName;
      this.favouriteColour = faveColour;
      this.greet = function () {
        return `Hello, my name is ${this.name} and my favourite colour is ${this.favouriteColour}`;
      };
    }

const john = new Person('John Doe', 'red');
john.greet();

const jane = new Person('Jane Doe', 'orange');
jane.greet();

const red = '#ff0000';
const orange = '#ffa500';
4

1 回答 1

1

我假设您想在某些 HTML 中显示具有指定颜色的文本。

如果是这种情况,您可以将在 greet 方法中返回的this.favouriteColour包装在一个跨度中,并添加一个动态样式。

参考以下:

function Person(fullName, faveColour) {
  this.name = fullName;
  this.favouriteColour = faveColour;
  this.greet = function () {
    return `
    Hello, my name is ${this.name} 
    and my favourite colour is 
    <span style="color:${faveColour}">${this.favouriteColour}</span>`;
  };
}

const john = new Person('John Doe', 'red');


const jane = new Person('Jane Doe', 'orange');


const red = '#ff0000';
const orange = '#ffa500';

const div1 = document.getElementById("app1");
div1.innerHTML = john.greet()


const div2 = document.getElementById("app2");
div2.innerHTML = jane.greet()
    <div id="app1"></div>
    <div id="app2"></div>

于 2020-12-08T19:23:32.377 回答