获取范围内的变量,而无需闭包/包装函数



如果我有一个随时间变化的变量,并且我想保留它的特定实例,我必须将其包装在闭包中,如下所示:

function test(){
	var x = Math.random();
	// Is there an alternative to using the following closure:
	var printnum = (function(num){ 
		return function(){
			console.log(num);
		}
	})(this.x); // Because I think this is ugly
	
	return printnum;
}
var a = test();
var b = test();
a(); //number
a(); //same as above
b(); //different number
b(); //same as above

在PHP中,您将使用如下use

$a = rand();
function () use ($a) {
  echo($a);
}

我真的很感激这一点,因为您可以立即看到正在注入的变量,它没有像 js 那样列在最底部: (function(b){})(a);也没有过多的括号。我尝试尝试使用 .apply().call(),但它们都执行函数,我只想在某种状态下注入一个变量。

我想我只是在要求一个不存在的语言功能,但请证明我错了。有什么想法吗?

一种使用 .bind(( (ES5( 删除包装器函数并避免闭包的简单方法:

function test(){
  return console.log.bind(console, Math.random());
}

你能用 es6 吗?如果是这样,箭头函数将给出相同的结果,但更简洁:

function test(){
	var x = Math.random();
  
	var printnum = x => () => console.log(x);
	return printnum(x);
  
    // OR you can invoke immediately:
    // var printnum = (x => () => console.log(x))(x);
    // return printnum;
}
var a = test();
var b = test();
a(); //number
a(); //same as above
b(); //different number
b(); //same as above

AFAIK,在javascript中,你必须以一种或另一种方式将x传递到函数中,以避免它在以后更改x值时打印其他内容。

我个人喜欢IIFE,但是"一个人的垃圾......"无论如何,您实际上只需要传递数字的副本,这样您就不会陷入闭包变量中。

function test(){
  // Because you are working with a number and JavaScript passes all arguments by value
  // a copy of the number will be passed to helper, allowing helper to "disconnect"
  // from using the number in the parent scope
  return helper(Math.random()); 
  
  function helper(num){
    return function(){ console.log(num); }
  }
}
var a = test();
var b = test();
a(); //number
a(); //same as above
b(); //different number
b(); //same as above

不需要

printnum函数。只需返回内部匿名函数。

这本质上与 PHP 相同,但它不需要 use() 声明来列出要继承到闭包中的变量(PHP 需要这个,因为默认值是不允许对外部变量进行任何访问(。

function test() {
  var x = Math.random();
  return function() {
    console.log(x);
  }
}
var a = test();
var b = test();
a(); //number
a(); //same as above
b(); //different number
b(); //same as above

最新更新