如何在javacript中编写可扩展的方法
我需要写一个方法,我将调用JavaScript中的字符串文字。 我想调用的方法如下所示:
"Javascript".toKampala();
这个功能是否存在于Javascript中? 如果它确实如何编写这样一个方法(toKampala())
的JavaScript文字或任何对象?
在Kotlin,我是这样做的;
fun String.toHenry():String{ return "$this Henry"; }
我可以打电话
"chalres".toHenry()
每个string
默认都有一个原型,它是String.prototype
对象,它可以访问在那里定义的任何东西。
您需要在String.prototype
添加该方法,并且可以从任何string
访问它。 你可以通过this
来访问该函数中的当前string
。
String.prototype.toHenry = function() { return this + ' Hentry'; }; console.log('charles'.toHenry());