Javascript 对象必须返回函数

Javascript 对象必须返回函数,javascript,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 +

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

您可以覆盖
toString
方法:

Car.prototype.toString = function() {
    return this.model + ' ' + this.year;
};
当需要对象的字符串表示时(例如,当您执行
“somestring”+您的对象
时),会自动调用此方法


参考:

您可以覆盖对象的方法:


您可以在控制台中测试结果。

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

如果你只是简单地把
console.log(bmw)
放进去,你会看到一个有趣的结果——取决于你使用的web检查器,你将能够点击bmw的所有属性……非常好

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

要回答您的精确问题,您可以通过重写对象的
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

因此,据我所知,每次调用对象时都会调用“toString”方法?否:仅当需要字符串表示时才调用。
“somestring”+AOObject
就是这种情况的一个例子。@FrédéricHamidi我将删除注释,但我不是向下投票人
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