gpt4 book ai didi

javascript - 在 javascript 中返回另一个函数是一个好方法吗?

转载 作者:行者123 更新时间:2023-12-02 19:03:48 26 4
gpt4 key购买 nike

当阅读一些javascript源代码时,我发现了下面的代码:

var fullname = function(){
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
return function(name){
return shorts[name] || name;
}
}();

返回另一个函数是更有效还是其他原因?为什么不使用:

    function fullname(name){
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
return shorts[name] || name;
}

最佳答案

这相当于

var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };

function fullname(name){
return shorts[name] || name;
}

...它的作用。但是

var fullname = function(){
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
return function(name){
return shorts[name] || name;
}
}();

...确保哈希/对象shorts,*仅对函数fullname私有(private)*.

所以回答你的问题,为什么不

  function fullname(name){
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
return shorts[name] || name;
}

这里的 shorts 隐藏在 fullname 中,但正如 Dogbert 指出的那样,它速度较慢因为哈希 shorts 是在每次调用时创建的。

但这提供了两全其美的优点:

var fullname = function(){
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
return function(name){
return shorts[name] || name;
}
}();

shorts全名保持私有(private)同时,shorts 仅实例化一次,因此性能会下降也要做个好人。

这就是他们所说的IIFE(立即调用函数表达式)。这个想法是在函数 B 内创建函数 A 并声明函数 A 使用的变量在函数 B; 的范围内,以便只有函数 A 可以看到它们。

 var B = function(){
// this is B
//
val foo = {x:1}; // this is ONLY for A

val A = function(arg0) {
// do something with arg0, foo, and whatever
// and maybe return something
};

return A;
};

val A = B();

如您所见,这与

相同
 var A = (function(){
// this is in 'B'
//
val foo = {x:1}; // this is ONLY for A

return function(arg0) { // this is in A
// do something with arg0, foo, and whatever
// and maybe return something
};

})(/*calling B to get A! */);

在功能上,这与

完全相同
 val foo = {x:1};  // foo is visible OUTSIDE foo!

val A = function(arg0) {
// do something with arg0, foo, and whatever
// and maybe return something**strong text**
};

我没有看到任何其他用途。所以这只是保持变量私有(private)的一种方式,并且同时,不损失性能。

(参见What is the (function() { } )() construct in JavaScript?)

关于javascript - 在 javascript 中返回另一个函数是一个好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14517832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com