[英]Simplifying creating modules with function and closure
This is from an example from a popular JS book that is exemplifying creating a module with the use of functions and closures. 这是来自流行的JS书籍的一个例子,该书例证了使用函数和闭包创建模块。 Simplified, the example looks like this
简化后,该示例如下所示
String.prototype.startify = function ( ) {
var startString = "Start ";
return function () { return startString + this;};
}();
console.log("Text".startify());
My question is, can this be reduced to the following since it seems to achieve the same result? 我的问题是,这可以减少到以下几点,因为它似乎达到了相同的结果吗? Also what is the purpose of returning a function and doing the last () ?
返回函数和执行last()的目的是什么?
String.prototype.startify = function ( ) {
var startString = "Start ";
return startString + this;
};
console.log("Text".startify());
The last ()
is invoking the function. last
()
正在调用该函数。 Imagine you have a function foo
想象一下,你有一个函数
foo
function foo() { }
If you want to run this function you call 如果你想运行这个功能,你打电话
foo();
Now if foo
returns a function 现在如果
foo
返回一个函数
function foo() {
return function bar() {
};
}
You can do 你可以做
var bar = foo();
bar(); // bar is a function
In you code 在你的代码中
String.prototype.startify = function ( ) { // foo
var startString = "Start ";
return function () { // bar
return startString + this;
};
}(); // () executes foo immediately
You are running the function "foo" and returning the function "bar" then storing it on the variable String.prototype.startify
. 您正在运行函数“foo”并返回函数“bar”,然后将其存储在变量
String.prototype.startify
。
foo
is only called once here, different from your second example. foo
只在这里调用一次,与你的第二个例子不同。
So as @Xufox said 所以@Xufox说
Imagine
var startString = "Start ";
想象一下
var startString = "Start ";
being a very complex expression.是一个非常复杂的表达。 In your second snippet, that expression would need to run every time you use startify.
在您的第二个代码段中,每次使用startify时都需要运行该表达式。 In the first example, it only needs to run once.
在第一个示例中,它只需要运行一次。
Also another advantage of this is that the variable startString
will not pollute the rest of the file or global with a variable you only use in a specific place, this variable will only exist in the function "foo". 此另一个优点是变量
startString
不会污染文件的其余部分或全局使用仅在特定位置使用的变量,此变量将仅存在于函数“foo”中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.