这只是一个概念证明。
在JavaScript中,"string"
是String
如果我有像Apple这样的特殊字符串,默认情况下应该像String一样:
预期行为:
var myFruit = new Apple('macintosh')
myFruit
的值应为"apple - macintosh"
当我创建一个数组时:
var myApple = new Apple('macintosh');
var myBanana = new Banana('chiquita');
var myFruits = [ myApple, myBanana ]
// ["apple - macintosh", "banana - chiquita"]
但是因为这个字符串是特殊类型的,所以如果我可以这样做的话会很酷:
myApple.setType("gala")
以及myApple
&&的价值myFruits[0]
将是"apple - gala"
我的假设是使用 defineGetter ,但它只适用于普通对象{}
,因为您必须定义object
的显式getter。
这是来自Mozilla的Object
参考:
// Non-standard and deprecated way var o = {}; o.__defineGetter__('gimmeFive', function() { return 5; }); console.log(o.gimmeFive); // 5 // Standard-compliant ways // Using the get operator var o = { get gimmeFive() { return 5; } }; console.log(o.gimmeFive); // 5 // Using Object.defineProperty var o = {}; Object.defineProperty(o, 'gimmeFive', { get: function() { return 5; } }); console.log(o.gimmeFive); // 5
因此,在我的方案中,getter
本身就是String object
,所以它有可能吗?
使用valueOf
和toString
var Fruit = function(fruit, type) {
this.fruit = fruit;
this.type = type;
}
Fruit.prototype.toString = Fruit.prototype.valueOf = function() {
return this.fruit + " - " + this.type
}
function apple(type) {
return new Fruit('apple', type)
}
var myApple = apple('macintosh')
// NICE
myApple + "" // apple - macintosh
myApple.toString() // apple - macintosh
// UUUPS
console.log(myApple) // => {fruit: "apple", type: "macintosh"}
JSON.stringify(myApple) // => {fruit: "apple", type: "macintosh"}