对象必须返回函数

时间:2012-08-23 11:17:35

标签: javascript

我在这里有一些JS代码:

function Car(manufacturer, model, year) {
    this.manufacturer = manufacturer;
    this.model = model;
    this.year = year == undefined ? new Date().getFullYear() : year;
    this.getInfo = function(){
        return this.manufacturer +' '+ this.model +' '+ this.year;
    };
}

var bmw = new Car("BMW", "X5", 2010);

所以我想在控制台中输出一些有趣的内容:

console.log('Car: ' + bmw); // Car: BMW X5 2010

如何在不调用任何方法的情况下执行此操作?

谢谢!

I need the 'getInfo' method, so I have simply changed my code:
function Car(manufacturer, model, year) {
    this.manufacturer = manufacturer;
    this.model = model;
    this.year = year == undefined ? new Date().getFullYear() : year;
    this.toString = this.getInfo = function(){
        return this.manufacturer +' '+ this.model +' '+ this.year;
    };
}

3 个答案:

答案 0 :(得分:1)

console.log只是向控制台输出它作为参数给出的内容。在你的情况下,你给它一个字符串(通过将一个字符串与一个对象连接起来)。

如果您只是简单地放置console.log(bmw),您会看到一个有趣的结果 - 根据您使用的网络检查员,您可以点击所有bmw的属性......非常好。

Chrome开发者工具中console.log(bmw)的代表:

enter image description here

要回答您的确切问题,您可以通过覆盖其toString()函数来更改对象的字符串表示形式。

function Car(manufacturer, model, year) {
    this.manufacturer = manufacturer;
    this.model = model;
    this.year = year == undefined ? new Date().getFullYear() : year;
    this.getInfo = function(){
        return this.manufacturer +' '+ this.model +' '+ this.year;
    };

    // Build the string up as you wish it to be represented.
    this.toString = function() {
        var str = this.manufacturer + " " + this.model + " " + this.year;
        return str;
    };
}

var bmw = new Car("BMW", "X5", 2010);
console.log('Car: ' + bmw); // Car: BMW X5 2010

答案 1 :(得分:0)

您可以覆盖toString方法:

Car.prototype.toString = function() {
    return this.model + ' ' + this.year;
};

当需要对象的字符串表示时(例如,当您执行"somestring" + yourObject时),将自动调用此方法。

参考:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/toString

答案 2 :(得分:0)

您可以覆盖对象的toString()方法:

function Car(manufacturer, model, year) {
    this.manufacturer = manufacturer;
    this.model = model;
    this.year = year == undefined ? new Date().getFullYear() : year;
    this.toString = function() {
        return this.manufacturer + ' ' + this.model + ' ' + this.year;
    };
}

您可以在this fiddle中测试结果。