3

我这里有一些 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;
    };
}
4

3 回答 3

1

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

如果您简单地说console.log(bmw),您会看到一个有趣的结果 - 根据您使用的网络检查器,您将能够单击所有bmw属性...非常好。

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

在此处输入图像描述

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
于 2012-08-23T11:23:18.460 回答
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

于 2012-08-23T11:20:09.383 回答
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;
    };
}

您可以在这个 fiddle中测试结果。

于 2012-08-23T11:20:33.150 回答