是否可以从JavaScript中的函数内的调用者范围访问变量?

时间:2018-03-08 01:48:32

标签: javascript variables ecmascript-6 scope closures

此问题之前已被问过,但所有热门问题都已超过5年,我很想知道自那时以来是否有任何变化。如果你有一个已定义的函数

const accessParentScope = () => parentVariable;

那么有没有办法从调用函数的范围访问parentVariable?最终目标是做类似

的事情
function createAnotherScope() {
  const parentVariable = 'some value';
  return accessParentScope();
}

并让accessParentScope()有权访问parentVariable ,而明确地将其作为参数传递。

或者,是否可以从闭包范围访问变量?如果你有像

这样的功能
function createClosure() {
  const parentVariable = 'some value';
  return closure = () => null;
}
那么你能做createClosure().parentVariable之类的事吗?这里的语法显然不起作用,但我很好奇是否有可能像这样远程。

2 个答案:

答案 0 :(得分:2)

  

是否可以在JavaScript中的函数内访问调用者范围内的变量?

没有。那将是dynamic scope。大多数语言(包括JavaScript)都实现lexical scope。这不会改变。

this,但它是一个明确传递的参数。 this的值(在大多数情况下)是在函数调用时确定的,而不是在定义它的时间或位置时(箭头函数对this的处理方式不同)。

function logName() {
  console.log(this.name);
}

function sayFoo() {
  logName.call({name: 'foo'});
}
sayFoo();

function sayBar() {
  logName.call({name: 'bar'});
}
sayBar();

正如您所看到的,与使用参数定义函数相比,这没有任何优势:

function logName(name) {
  console.log(name);
}

function sayFoo() {
  logName('foo');
}
sayFoo();

function sayBar() {
  logName('bar');
}
sayBar();

正如@JaromandaX在评论中所说的那样,这就是参数在调用时为函数提供值的原因。

答案 1 :(得分:1)

  

有没有办法从调用该函数的作用域中访问parentVariable

没有。唯一的方法是,如果声明了箭头函数的上下文具有该属性或变量可用。

var parentVariable = 'Ele from SO'; // This is the variable available to the below arrow function (window context).
const accessParentScope = () => parentVariable; // or this.parentVariable

function createAnotherScope() {
  const parentVariable = 'some value';
  return accessParentScope();
}

console.log(createAnotherScope())

  

或者,是否可以从闭包范围访问变量?

是的,这样就可以访问声明的属性和局部变量。

function createClosure() {
  this.parentVariable = 'some value'; // Note that this is an attribute (global as well) rather than a local variable.
  return closure = () => this.parentVariable;
}

console.log(createClosure()());
console.log(parentVariable);  // Access to global variable/attribute

  

然后你可以做一些像createClosure()。parentVariable?

不,你可以做的是为返回的函数设置一个属性。

function createClosure() {
  var closure = () => closure.parentVariable
  closure.parentVariable = 'some value';
  
  return closure;
}

console.log(createClosure()());
console.log(createClosure().parentVariable)

相关问题