新发展理念新功能
Douglas Crockford once said that JavaScript was the only language developers didn't need to learn to use. That's as true a statement as you'll hear when it comes to programming. We all sort of stumbled into JavaScript, mostly due to JavaScript frameworks which made JavaScript magical and easy. "Anonymous function? No idea what that is but the example looked like that so that's what I do."
道格拉斯·克罗克福德(Douglas Crockford)曾经说过,JavaScript是开发人员不需要学习的唯一语言。 就像您在编程时会听到的那样,这确实是一条声明。 我们几乎都迷上了JavaScript,主要是由于JavaScript框架使JavaScript变得神奇而又简单。 “匿名函数?不知道那是什么,但示例看起来像这样,这就是我要做的。”
One thing you may not know about JavaScript functions is that you can pass new Function()
the function's body in a string. It isn't something you'd do often but it can be useful
您可能不了解JavaScript函数的一件事是,您可以将new Function()
函数传递给字符串。 这不是您经常要做的事情,但它可能会很有用
JavaScript (The JavaScript)
Here's the basic usage of new Function:
这是新功能的基本用法:
var myFunction = new Function('users', 'salary', 'return users * salary');
The last argument to Function is the function body as a string, and the previous arguments represent different arguments to the function. Fairly easy, right?
Function的最后一个参数是作为字符串的函数主体,而前面的参数代表函数的不同参数。 相当容易,对吧?
The question is: what is the use case for this, instead of the tradition function myFnName()
and anonymous function definitions? Andrea Giammarchi believes that this pattern is the best way to get the global within NodeJS and the browser:
问题是:用它代替传统function myFnName()
和匿名函数定义是什么? Andrea Giammarchi认为,这种模式是在NodeJS和浏览器中获得全局性的最佳方式 :
(function(win) {
// Do something with the global
})(Function('return this')());
If you've used the new Function pattern before, let me know what you've used it for. I'd love to hear about it!
如果您以前使用过新的功能模式,请告诉我您使用它的目的。 我很想听听它!
新发展理念新功能