gpt4 book ai didi

javascript - 在 if 语句中使用对象时会调用什么 native 函数?

转载 作者:行者123 更新时间:2023-12-02 15:23:23 25 4
gpt4 key购买 nike

我正在尝试构建一个可在 if 语句中使用的模块来检查某个值是 true 还是 false。这个想法是你做这样的事情:

var module = require('nice-module')

if(module) {
console.log('The rumors are definitely true')
}

但是,我希望这个东西是可配置的,以一种可能的方式:

var module = require('nice-module')

module.configure({ theDress: 'blue with black'})

if(module) {
console.log('The rumors are still true')
} else {
console.log('Based on this new information you have given the answer is now no')
}

我尝试创建一个覆盖标准 Object.valueOf() 函数的对象,这样我就可以拥有一个具有自己的函数和属性的常规对象,但让它调用某个函数并在 if 语句内部使用时返回 truefalse。它看起来像这样:

module.exports = {
theDress: 'white with gold',

configure: function(configuration) {
this.theDress = configuration.theDress
},

valueOf: function() {
return this.theDress === 'white with gold'
}
}

然而,令人惊讶的是,它不起作用。我尝试将 valueOf()toString() 交换或为两者分配相同的函数。我在该对象上尝试了console.log(),它似乎也没有调用我的函数,只是给了我完整的对象,无论我使用哪种实现。我是否执行了错误的覆盖操作? JavaScript 在评估某事物是真还是假时不使用 valueOf() 吗?

最佳答案

没有调用任何函数,非空对象不可能是假的。

参见the MDN :

In JavaScript, a truthy value is a value that translates to true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

我想到了两种解决方案,对于用户来说也可能更清晰:

  • 使用特定函数来提供该功能。它
  • 如果配置失败则抛出异常(我不清楚您的用例)

关于javascript - 在 if 语句中使用对象时会调用什么 native 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33890150/

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