Javascript对象构造函数&布尔变量

时间:2013-01-12 09:28:39

标签: javascript object constructor boolean

我正在尝试创建一个JS Object构造函数,但是想要使用布尔操作声明该对象的一个​​属性。不知怎的,我错了 - 请指教!

谢谢! A.C。

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 个答案:

答案 0 :(得分:2)

这是为您修复的学生功能。使用ternary if语句代替你的“Boolean(){}”,它实际上是无效的Javascript代码+布尔值是真或假,你返回“成人”或“次要”这是字符串,并不真正匹配无论如何都是布尔类型

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");
} 

答案 1 :(得分: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",如果为false则为"minor"

答案 2 :(得分: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/

答案 3 :(得分:0)

其他人告诉你应该做什么,但如果你需要的不仅仅是一个布尔三元,那么这就是你的代码精神的答案。

this.age = (function () {
    if (age >= 21) {
        return "adult";
    } else {
        return "minor";
    }     
}();