繁体   English   中英

如何在Javascript的预定义全局变量中使用原型函数?

[英]How to use the prototype functions in predefined global variables in Javascript?

请告诉我如何在预定义变量中使用注入的函数。 这是将字符串转换为驼峰式大小写的脚本,但是我不知道如何使用它。

String.prototype.toCamelCase = function(str) {
    return str
        .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
        .replace(/\s/g, '')
        .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

另外,告诉我使用$1作为参数是否有意义! 我的意思是此功能中有$用途吗?

附言:我从这个问题中得到了这个脚本。

另外,告诉我使用$1作为参数是否有意义! 我的意思是此功能中有$用途吗?

不,这只是param的名字。

请告诉我如何在预定义变量中使用注入的函数。 这是将字符串转换为驼峰式大小写的脚本,但是我不知道如何使用它。

  • 您只需要实例化该类型(字符串)的变量。
  • 当您需要对特定对象进行操作时,原型非常有用,因此您不需要传递字符串,而是使用当前上下文this (在这种情况下为字符串)。

 String.prototype.toCamelCase = function() { return this // Here you use the current object using the context 'this' .replace(/\\s(.)/g, function($1) { return $1.toUpperCase(); }) .replace(/\\s/g, '') .replace(/^(.)/, function($1) { return $1.toLowerCase(); }); } console.log("ele from so".toCamelCase()); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM