使用 include 函数在 JavaScript 中缺少 this.name 时不会抛出错误

Error not being thrown when missing this.name in JavaScript using includes function

class Speaker {
    constructor(name) {
        this.name = name;
    }
    get Message() {
        if (!this.message.includes(this.name)) {
            throw Error("message is missing speaker's name");
        }
        return this.message;
    }
    set Message(val) {
        let tmpMessage = val;
        if (!val.includes(this.name)) {
            tmpMessage = this.name + " " + val;
        }
        this.message = tmpMessage;
    }
}
const speaker = new Speaker();
speaker.Message = "hello";
console.log(speaker.Message);

我从一本书中得到了这段代码。我很困惑为什么当我 运行 它时没有抛出错误,因为在书中声明它确实如此。相反,我得到 undefined Hello 有人可以对此有所了解吗?

它没有抛出错误,因为 !this.message.includes(this.name) 没有得到满足。

在你的例子中,

speaker.Message = "hello";

当你调用它时,你正在内部检查 !val.includes(this.name)。这里 this.nameundefined 所以,!val.includes(this.name) 将是 true 并且保存的消息是 undefined hello.

并在通话中

console.log(speaker.Message);

您正在检查 !this.message.includes(this.name),这里 this.nameundefinedthis.messageundefined hello

最终 !this.message.includes(this.name) 将是 false。因此 this.message 被返回,即 undefined hello 这就是为什么没有抛出错误的原因。

//!this.message.includes(this.name) --> 
//this condition gets evaluated like below, hence error is not thrown
console.log(!"undefined hello".includes(undefined));