【问题标题】:Is it possible to access a variable from the caller's scope inside a function in JavaScript?是否可以从 JavaScript 函数内的调用者范围访问变量?
【发布时间】:2018-08-16 06:35:43
【问题描述】:

以前有人问过这个问题,但所有热门问题都是 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 的事情吗?这里的语法显然行不通,但我很好奇这样的远程操作是否可行。

【问题讨论】:

  • 这就是发明函数参数的目的——将值传递给函数
  • 不,不(不,这不会改变)。你认为你需要这个做什么,你的actual problem是什么?

标签: javascript variables ecmascript-6 scope closures


【解决方案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)

【讨论】:

  • 在您的第一个示例中,const accessParentScope = () => parentVariable; 也可以。不需要this。在您的第二个示例中,this 是全局对象(因此您正在隐式创建全局变量)或 undefined(在这种情况下代码会引发错误)。
  • @FelixKling 1.) 是的,2.) 是的
【解决方案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 在他们的评论中所说,这就是参数的含义,以便在调用时为函数提供值。

【讨论】:

    猜你喜欢
    • 2010-11-16
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多