gpt4 book ai didi

javascript - 这个 charcode bool 语句有什么问题?

转载 作者:行者123 更新时间:2023-11-28 11:37:44 25 4
gpt4 key购买 nike

我在类对象中有一个 if/else 语句。 if 检查 bool 语句,但返回错误结果。

function person(name) {
this.name = name;
this.age = (function age() {
if (this.name.toLowerCase().charCodeAt(0) <= "n".charCodeAt(0)) {
return "A";
}
else {
return "B";
}
})();
}

var zoey = new person("Zoey");


console.log(zoey.name);
console.log(zoey.age); // returns A

console.log("Zoey".toLowerCase().charCodeAt(0)); // returns 122
console.log("n".charCodeAt(0)); // returns 110

如果我将 bool 语句中的“this.name”更改为“name”,它就会起作用。知道为什么吗?

最佳答案

您立即调用的函数表达式正在创建一个新作用域,其中 this 的上下文发生变化。当您仅使用 name 时,您指的是传递到构造函数中的参数。您可以缓存this绑定(bind)它来维护上下文:

var self = this;
this.age = (function age() {
if (self.name...)
}());

// In modern browsers
this.age = (function age() {
if (this.name...)
}.bind(this)());

关于javascript - 这个 charcode bool 语句有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com