gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:44:23 24 4
gpt4 key购买 nike

我有一个返回对象的函数

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*/

关于javascript - 如何从对象返回可读字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20407592/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com