if 语句在函数中有效,但在 setter 方法中无效,反之亦然,setter 也根本不起作用
我正在 CodeCademy 上做一个项目,我需要为一些学生创建一个 setter 方法。它应该检查该值是否是数字,如果是,则返回该值,否则记录错误。我最初想出了这段代码
set numberOFStudents(val) {
if(typeof val === 'number') {
this._numberOfStudents = val;
} else {
console.log('Invalid input: numberOfStudents must be set to a Number.')
}
}
,但它不起作用,因为该值没有效果。它将返回字符串和数字作为值。 但是,当我在常规函数中使用此方法时,它完美地工作 https://jsfiddle.net/蒙蒂耶克/v8zsL5et/12/ 本演练中使用的方法是这样的:
set numberOfStudents(val) {
if(val.isNaN()) {
console.log('Invalid input: numberOfStudents must be set to a Number.')
} else {
this._numberOfStudents = val;
}
}
这在常规函数中不起作用,因为它返回错误 https: //jsfiddle.net/Montinyek/e6k7qdcs/ 但更让我困惑的是,演练中使用的方法似乎也没有效果。我仍然可以将学生人数设置为字符串,它会记录它,而不是记录错误。这是整个代码的jsfiddle https://jsfiddle.net/Montinyek/1j7wL5gm/
I'm doing a project on CodeCademy and I need to create a setter method for a number of students. It should check if the value is a number and if it is, return the value, otherwise log an error. I initially came up with this code
set numberOFStudents(val) {
if(typeof val === 'number') {
this._numberOfStudents = val;
} else {
console.log('Invalid input: numberOfStudents must be set to a Number.')
}
}
But it didn't work as the value had no effect. It would return both strings and numbers as values.
However, when I use this method in a regular function, it works perfectly https://jsfiddle.net/Montinyek/v8zsL5et/12/
The method used in the walkthrough was this:
set numberOfStudents(val) {
if(val.isNaN()) {
console.log('Invalid input: numberOfStudents must be set to a Number.')
} else {
this._numberOfStudents = val;
}
}
Which doesn't work in a regular function as it returns an error https://jsfiddle.net/Montinyek/e6k7qdcs/
But here's what confused me even more, the method used in the walkthrough doesn't seem to have an effect either. I can still set the number of students to a string and it will log it, instead of logging an error. Here's the jsfiddle of the entire code https://jsfiddle.net/Montinyek/1j7wL5gm/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为您没有在构造函数中使用设置器。因此,当您传入字符串时,它会分配它。
您需要更改
To,
以便它使用 setter 而不是成员变量。第一种方式直接将其分配给您的成员,而不是使用 setter。
这是根据您的示例进行更改的完整代码;
这是保存的 jsfiddle,显示其工作
https://jsfiddle.net/6qoadu27/6/
Its because your not using the setter in your constructor. So when you pass in the string it assigns it.
You need to change
To
so it uses the setter and not the member variable. The way in the first directly assigns it to your member instead of using the setter.
Here is the full code with the change as per your example;
here is the saved jsfiddle showing its working
https://jsfiddle.net/6qoadu27/6/