在javascript中得到空白输出

时间:2014-05-02 14:16:48

标签: javascript

嘿伙计们我在javascript中尝试了一些复杂类型的代码。但是我给了一个空白页面..我试过的代码是

var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566
};

var b = function() {
    return null;
}

person.b({
    name: "yipee",
    age: "20"
});

var somebody = new person();

console.log(somebody.person.b().name);

我需要的结果是yipee ..但我得到一个空白页而不是那个..如果我在这段代码上做错了什么请帮助我...希望你们能帮助我

4 个答案:

答案 0 :(得分:1)

您收到了js错误,这可能是空白页面的原因。

您正在尝试调用该函数' b'在对象'人物'这并不存在。

console.log(somebody.person.b().name);

' B'总是返回null,这一行永远不会起作用

您需要以下内容:

var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    b : function(/* parameters */)
    {
        // do something
        // return something
    }

};

此外:

var somebody = new person();

'人'不是一个功能,所以你不能打电话给新的'在它上面。

答案 1 :(得分:1)

尝试创建一个Person函数作为构造函数来初始化new实例并将b附加到其原型,以便可以将其作为方法调用。

目前还不清楚您希望代码执行什么操作,但这里有定义Person的内容,从数据包中创建一个,并调用b以获得完整名。

function Person(fields) {
  this.firstName = String(fields.firstName);
  this.lastName = String(fields.lastName);
  this.id = Number(fields.id);
  this.age = Number(fields.age);
}
Person.prototype.b = function() {
  return this.firstName + " " + this.lastName;
};

var sombody = new Person({
  firstName: "yipee",
  age: "20"
});

console.log(somebody.b());

另请参阅"Falsehoods programmers believe about names",了解为什么第一个/最后一个是表示姓名的不良方式。

答案 2 :(得分:-1)

使用原型添加

person.prototype.b({
name: "yipee",
age: "20"
});

答案 3 :(得分:-1)

好像您试图在b对象上设置person方法,但假设您要做的只是将另一个对象存储在b中,您最好的选择是只需将其定义为person的属性:

var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566
};

// Note this function 'b' is completely unrelated to the person
// object that you have defined
var b = function() { return null; };

person.b = {
  name: "yipee",
  age: "20"
};

// I've commented out your attempt to instantiate a new person object 
// because you cannot call `new` on a JS object as you have done. Notice
// how you are calling person with a set of parens, indicating that you
// wish to treat it as a function. Since person is a generic object, not
// a function object, this call to new will not return anything useful

// var somebody = new person();

console.log(person.b.name);
=> "yipee"

或者,如果您希望person.b成为方法调用,则可以这样定义:

person.b = function() {
  return {
    name: "yipee",
    age: "20"
  }
};

person.b().name;
=> "yipee"