0

我正在尝试创建一个 JS 对象构造函数,但想使用布尔运算声明对象的属性之一。不知何故我弄错了 - 请指教!

谢谢!交流电

function Student(gender, name, id, age, likes) {
this.gender = gender;
this.name = name;
this.id = id;
this.age = Boolean () {
    var age = x;
    if (age >= 21) {
    return "adult";
    } else {
    return "minor";
  }     
  };
this.likes = likes;
 }

window.onload = init;

function init() {
var jessica = new Student("female", "Jessica", 12, 21, ["butterflies", "flowers", "music"]);
var jessicaJSON = JSON.stringify(jessica);
console.log(jessicaJSON);

var anotherJessica = JSON.parse(jessicaJSON);
console.log(anotherJessica);

}
4

4 回答 4

2

这是为您修复的学生功能。使用三元 if 语句而不是真正无效的 "Boolean() {}"无论如何都是布尔类型。

function Student(gender, name, id, age, likes) {
  this.gender = gender;
  this.name = name;
  this.id = id;
  this.likes = likes;
  this.age = (age >= 21 ? "adult" : "minor");
} 
于 2013-01-12T09:39:49.183 回答
1

我想这就是你需要的:

function Student(gender, name, id, age, likes) {
  this.gender = gender;
  this.name = name;
  this.id = id;
  this.age = (age >= 21) ? "adult" : "minor";
  this.likes = likes;
}

var jessica = new Student("female", "Jessica", 12, 21, ["butterflies", "flowers", "music"]);
console.log(jessica.age); //adult

这里我使用三元条件运算符:condition ? value_if_true : value_if_false.

在这种情况下,条件是age >= 21,如果为真"adult",则值为,如果为假,则值为"minor"

于 2013-01-12T09:40:23.893 回答
0
function Student(gender, name, id, age, likes) {
    this.gender = gender;
    this.name = name;
    this.id = id;
    this.age = (age >= 21) ? "adult":"minor";
    this.likes = likes;
}

示例:http: //jsfiddle.net/av5ym/1/

于 2013-01-12T09:40:58.247 回答
0

其他人告诉你你应该做什么,但这里有一个本着你的代码精神的答案,以防你需要的不仅仅是一个布尔三元。

this.age = (function () {
    if (age >= 21) {
        return "adult";
    } else {
        return "minor";
    }     
}();
于 2013-01-12T09:45:09.777 回答