繁体   English   中英

对象必须返回函数

[英]Object must return function

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

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

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

Chrome Developer Tools中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方法:

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

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

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

您可以覆盖对象的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;
    };
}

您可以在这个小提琴中测试结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM