如何在Javascript构造函数中使用布尔值?
我有一个构造器,我想做一些我似乎无法开始工作的事情如何在Javascript构造函数中使用布尔值?,javascript,object,constructor,boolean,Javascript,Object,Constructor,Boolean,我有一个构造器,我想做一些我似乎无法开始工作的事情 我想用行星参数强制一个布尔值。我可以使用表单验证来手动格式化它,但我不知道如何在JS中实现它,这让我感到困扰 我想在此构造函数中插入一个日期。同样,我可以在前端处理它,但我想在这里处理它 var telescope = []; function newStar(name, color, planet) { this.name = name this.color = color this.planet = planet
- 我想用行星参数强制一个布尔值。我可以使用表单验证来手动格式化它,但我不知道如何在JS中实现它,这让我感到困扰
- 我想在此构造函数中插入一个日期。同样,我可以在前端处理它,但我想在这里处理它
var telescope = []; function newStar(name, color, planet) { this.name = name this.color = color this.planet = planet // interpreted as "Is a planet?" true/false telescope.push(this) } var a = new newStar("sol", "yellow", false) var b = new newStar("mars", "red", true) console.log(telescope)
if (typeof planet !== 'boolean') {
throw TypeError('planet should be Boolean');
}
// do something here
对于“我想在此模型中插入日期”,不确定您的要求是什么?您可以像这样在其中添加日期
var telescope = [];
function newStar(name, color, planet) {
this.name = name
this.color = color
this.planet = planet // interpreted as "Is a planet?" true/false
this.create_date = new Date();
telescope.push(this)
}
var a = new newStar("sol", "yellow", false)
var b = new newStar("mars", "red", true)
console.log(telescope)
不过我先不明白。你能解释一下你想要什么吗?嗯,什么?试着准确地解释一下你想做什么?你知道javascript都是前端,对吗?(除了NodeJS)@RUJordan是的,我知道JS是前端。我不想将代码实现到一个成熟的项目中。我想自己使用它。@adeneo我想告诉JS期望一个布尔值,而不仅仅是能够理解一个布尔值(我甚至不确定在没有外部结构/资源的情况下这在技术上是否可行)。因此,如果我理解正确,就无法告诉构造函数本身某个值必须是某个类型。如果要查找特定的值,只需编写一个if语句来检查它。对吗?是的,在ECMAScript(通常称为JavaScript)中您不能将变量的值限制为某种类型,因为它是一种动态类型的语言。谢谢您,先生。您是一名昆杜和学者;)对于日期部分,这正是我想要的。我在调用函数时一直尝试使用date(),认为它在构造函数中不起作用。谢谢!