javascript - 获取 javascript 函数实例本身以启用文档字符串。是否可以?

标签 javascript string class overloading

乌托邦目标:

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/

相关文章:

c++ - 读取私有(private)变量类成员

C# - 如何检查 C# 中是否存在命名空间、类或方法?

javascript - 为什么 ng-click 被称为按钮被点击的次数?

javascript - 如何在 page.goto 函数中为每个请求设置超时选项

javascript - 如何在 spring mvc 中将数组变量从 View 传递到 Controller

javascript - iOS:加载 javascript 并将其注入(inject)网页的最快方法?

c - 从字符串中提取整数

C 程序在尝试使用指针访问字符串数据时不打印文本

用于轮式选择器的 Android 阵列

java - 访问封闭类或父类的方法的一般方法