在 Ruby 中,您可以编写类似 "hello".upcase
的内容,而在许多其他语言(例如 Javascript 和 Elm)中,这需要像 String.upcase("hello")
这样的样式。这感觉是多余的。
当库的名称表示函数某个参数的数据类型(例如 String.upcase(string_type_argument)
等函数)时,是否有任何语言实现与核心数据类型(字符串、列表/数组等)相关的函数的简写? ),也许[special character]upcase(string_type_argument)
?这有优点还是缺点吗?
我意识到,在 Elm 中,一种选择是导入函数(例如 import String exposing (..)
或 import String exposing (some, specific, functions)
),但它们很困惑(导入具有可能重叠的函数名称的整个核心库),或者烦人的额外工作(使特定的函数导入与正在使用或未使用的函数保持同步)。
最佳答案
JavaScript 使用原型(prototype),以字符串为例:
String.prototype
本质上是所有字符串操作方法的容器。
示例:
String.prototype.toUpperCase = function() {
// makes the string uppercase and returns it
// this is a native method
}
您可以简单地在任何字符串上调用此函数,如下所示:
'var name = 'john';
name.toUpperCase() = //JOHN;'
或者甚至:
'john'.toUpperCase();
现在,我们假设 toUpperCase 函数不存在,我们必须复制它的功能
我们可以通过几种方式实现:
将其添加到 String.prototype:
String.prototype.NEWUPPERCASEFUNCTION = function() {
// we can refer to the 'string' that is always left of the dot with 'this'
// which is a reserved word in JS:
return 'this' in uppercase
}
这通常会被皱眉,并且可能会导致问题
另一种更常见的方法是,只创建一个函数,在其中传递一个字符串并返回该字符串的大写版本,或者“大写”后的该字符串:
function upperCaser(string) {
// not gonna write out the logic here, but you get it
return updated string
}
关于javascript - 为什么或为什么不为某些数据类型的核心函数提供简写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36381173/