乌托邦目标:
str = "hello"
str.doc = "this is a string"
console.log(str) //prints 'hello'
console.log(str.doc) //should prints the docstring
但是,字符串是不可变的,上述情况是不可能的。
我是如何尝试变通的:
str = new String("hello")
str.doc = "this is a string"
console.log(str) //prints the string object but not 'hello'
console.log(""+str) //prints "hello"
console.log(str.doc) //correctly prints the docstring
如您所见,只有在调用 .valueOf() 或 .toString() 时,您才能获得原始字符串。目标是在直接调用时获取字符串。
另一种解决方法(在 coffescript 中,为了简短起见:3 行 vs ~15 行)
class Configuration
constructor: (@value, @doc) ->
@::valueOf = -> @value
这与 new String()
非常相似。它只是对对象的 valueOf()
方法进行原型(prototype)化。问题和上面一样。您不能直接使用 console.log(str)
打印原始字符串,两者都使用 console.log(str.doc)
问题:
是否有可能以某种方式实现这一点,而不必重构我的整个代码库?
最佳答案
您可以对字符串进行原型(prototype)设计。参见 fiddle
// String.prototype.__defineGetter__("doc", function() { return "test" }); //deprecated
Object.defineProperty(String.prototype, "doc", {
get: function doc() {
return "this is a string";
}
});
console.log("this is a string".doc);
关于javascript - 获取 javascript 函数实例本身以启用文档字符串。是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36215095/