我如何打印构造函数的值?

时间:2013-07-13 10:05:17

标签: javascript

我想打印鲍勃·史密斯和他的年龄,我该怎么做?该示例是codecademy上面向对象系列的一部分,任何帮助都将非常感激。

function Person(name, age) {
    this.name = name;
    this.age = age;
};
// Let's make bob again, using our constructor
var bob = new Person("Bob Smith", 30);
var susan = new Person("Susan Jordan", 35);
// make your own class here
console.log(this.name);

2 个答案:

答案 0 :(得分:2)

如果您想打印Bob的名字,请打印bob的{​​{1}}:

name

答案 1 :(得分:0)

function Person(name, age) {
    this.name = name || '';
    this.age = age || -1;
};

Person.prototype.toString = function(){
    return this.name + ' ' + this.age;
};

var bob = new Person("Bob Smith", 30);

console.log(bob.toString());
alert(bob);