如何从对象返回可读字符串

How to return a readable string from an object

本文关键字:字符串 返回 对象      更新时间:2024-03-19

我有一个函数,它返回一个对象

function a(){
    return {
        b:1,
        c:2
    }
}

执行a().b将成功返回1,但在调用a()时,我也想返回除[object object]之外的其他内容。像这样的

function a(){
    return {
        b:1,
        c:2
        toString: 'you got 2 values'
    }
}

会呈现出类似的东西

alert(a()) // you got 2 values

有可能吗?

您需要定义类a,并在其定义中添加函数toString

function a(){
    var _this = this;
    _this.b = 1;
    _this.c = 2;
    _this.toString =  function(){return 'you got 2 values';};
    return _this;
}

现在您可以直接调用a上的toString函数:

a().toString(); /*executes the function and returns 'you got 2 values'*/

或者,您可以从类d中实例化一个对象,您可以调用内部函数:

d = new a(); 
d.toString(); /*returns the same value*/