简体   繁体   English

一线式将原型方法转换为JavaScript中的函数

[英]One-liner to change a prototype method into a function in JavaScript

The String object in Javascript has a method called toLowerCase . Javascript中的String对象具有一个称为toLowerCase的方法。 The problem with that method is that it requires that you already have a String object. 该方法的问题在于它要求您已经有一个String对象。

What if I wanted to turn that prototype method into a function that could be called on a String? 如果我想将该原型方法转换为可以在String上调用的函数,该怎么办?

I know that I can do this: 我知道我可以这样做:

var f = function (str) { return str.toLowerCase(); }
f("HI") // = "hi"

I want to avoid using the function keyword. 我想避免使用function关键字。

I thought that, since I can do this... 我以为,因为我可以做到...

String.prototype.toLowerCase.call("HI") // = "hi"

...that I could then do this: ...然后我可以这样做:

var f = String.prototype.toLowerCase.call
f("HI")

But this results in an error: 但这会导致错误:

Uncaught TypeError: f is not a function

Same goes for apply and bind . 同样applyapplybind

I want the resulting function to be callable using f("HI") , so using call and apply aren't allowed. 我希望使用f("HI")可以调用结果函数,因此不允许使用callapply

Is there way to accomplish this without resorting to using function ? 有没有办法不使用function来完成此操作?

For those of you who will inevitably wonder why I won't use the function keyword, it's just curiosity to help me understand JavaScript better. 对于那些不可避免地想知道为什么我不使用function关键字的人,只是出于好奇,可以帮助我更好地理解JavaScript。 I'm not trying to be fancy, or efficient, or anything. 我并不是想变得花哨,效率高或其他任何东西。 I'm not trying to optimize prematurely, etc., so please refrain from Knuth quotes. 我不是在尝试过早优化,等等,因此请不要使用Knuth引号。

Got it. 得到它了。 Quite a mental puzzle you put together, and I wasn't sure there was any way to have the first argument be accepted how we want it. 您拼凑了一个很困惑的难题,但我不确定是否有任何方法可以让我们接受第一个论点。

var pointlessFunctionBindingForJavascriptHackers =
   Function.prototype.call.bind(String.prototype.toLowerCase)

Is it cheating to precreate an demethodize function? demethodize功能是否作弊?

function demethodize(meth) {
    return function () {
        return Function.prototype.call.apply(meth, arguments);
    }
}

var f = demethodize(String.prototype.toLowerCase);

At least, I hope this may satisfy your "help me understand JavaScript better" requirement. 至少,我希望这可以满足您的“帮助我更好地理解JavaScript”要求。 :-) :-)

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

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