Kolink 是绝对正确的,只要您希望该值是一个字符串,那么您可以将值“装箱”到一个对象中,然后覆盖 toString 方法。但是,所做的只是允许javascript(当它需要将对象输出为字符串时)输出变量(通过为您本机调用toString)。它不是返回原始值,而是一个装在另一个对象中的值。
我想指出几件事情,以说明两者的差异(举几个例子)。所以,让我们来看看以下内容:
var BoxedString = {
value: 'Hello, world!',
toString: function(){ return this.value; }
};
var BoxedNumber = {
value: 3.14,
toString: function(){ return this.value; }
};
var BoxedDate = {
value: new Date(), // today
toString: function(){ return this.value; }
};
很简单,我们可以在必要时将这些中的每一个输出为字符串(或者我们可以吗?)
// Each of these implicitly calls `.toString()` because we're concatenating
// them within another string. Metho calls (like `alert()` that look for a
// string result have the same effect.
console.log('BoxedString: '+BoxedString); // BoxedString: Hello, world!
console.log('BoxedNumber: '+BoxedNumber); // BoxedNumber: 3.14
console.log('BoxedDate: '+BoxedDate); // fail!
等等,BoxedDate 失败;这是为什么?因为我们的toString 正在返回Date 对象,并且不能按原样输出。但是,如果我们将BoxedDate.toString 更改为返回this.value.toString(),我们会看到更好的结果(继续尝试,我会等待。)
让我们坚持BoxedDate 趋势并尝试日期方法:
console.log(BoxedDate.getFullYear()); // BoxedDate.getFullYear is not a function
再一次,它实际上不是Date,而是包裹在闪亮盒子中的Date。奇怪的是,Javascript 知道的足够隐式转换 BoxedNumber:
var sum = 38.86 + BoxedNumber; // 42 (works)
但是,不要尝试任何Number 对象方法,例如toFixed()。与BoxedString 和.replace()、toUpperCase() 等字符串方法相同。
不过,如果我要在 @Kolink 的答案中添加一些内容,则还应包括 valueOf 作为对象声明的一部分。比如:
var BoxedValue = {
value: 2013,
toString: function(){ return this.value.toString(); }
valueOf: function(){ return this.value; }
};