现在,在我问问题之前,我只想说我知道字符串在 js 上是原始的,并且我知道你不能向它们添加属性。只是为了在有人提出之前解决这个问题。
我的问题是是否可以使对象具有某种默认值,就像日期对象具有默认值一样。对于日期对象,如果您执行 typeof date
,它将返回 "object"
,但如果您将其放入字符串中,它将自动更改为看起来像 >“2000 年 1 月 1 日星期日 01:23:45 GMT+0000 (ABC)”
。
是否可以创建一个具有相同行为方式的对象?或者这种行为是日期对象所独有的?
我可以使用它的一个例子是运行一个函数时,我想默认返回一个字符串,但同时也发送额外的数据。例如:
function getUser(index) {
return {
defaultVal: userNames[index],
extraData: {points:userPoints[index]}
}
}
alert("your name is "+getUser(userId))
//will alert the user's name, instead of json object
最佳答案
我相信您想重写 toString()
方法。
getUser.prototype.toString() = function() {
return this.stringRepresentation;
};
关于javascript - 为对象创建 "default"值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20929300/