28

JavaScript 具有词法作用域,这意味着从函数内访问的非局部变量在定义时解析为该函数的父级作用域中存在的变量。这与动态作用域形成对比,在动态作用域中,从函数内访问的非局部变量在调用时解析为该函数的调用作用域中存在的变量。

x=1
function g () { echo $x ; x=2 ; }
function f () { local x=3 ; g ; }
f # does this print 1, or 3?
echo $x # does this print 1, or 2?

上面的程序在词法范围的语言中打印 1 然后 2,在动态范围的语言中打印 3 然后 1。由于 JavaScript 是词法范围的,它会先打印 1,然后再打印 2,如下所示:

var print = x => console.log(x);

var x = 1;

function g() {
    print(x);
    x = 2;
}

function f() {
    var x = 3;
    g();
}

f();           // prints 1

print(x);      // prints 2

尽管 JavaScript 不支持动态作用域,但我们可以使用eval如下方式实现它:

var print = x => console.log(x);

var x = 1;

function g() {
    print(x);
    x = 2;
}

function f() {
    // create a new local copy of `g` bound to the current scope
    // explicitly assign it to a variable since functions can be unnamed
    // place this code in the beginning of the function - manual hoisting
    var g_ = eval("(" + String(g) + ")");
    var x = 3;
    g_();
}

f();                         // prints 3

print(x);                    // prints 1

我想知道是否存在另一种可能的方法来实现相同的结果而不诉诸eval.

编辑:这是我试图在不使用的情况下实现的eval

var print = x => console.log(x);

function Class(clazz) {
    return function () {
        var constructor;
        var Constructor = eval("(" + String(clazz) + ")");
        Constructor.apply(this, arguments);
        constructor.apply(this, arguments);
    };
}

var Rectangle = new Class(function () {
    var width, height;

    constructor = function (w, h) {
        width = w;
        height = h;
    };

    this.area = function () {
        return width * height;
    };
});

var rectangle = new Rectangle(2, 3);
print(rectangle.area());

我知道这不是一个很好的例子,但总体思路是使用动态范围来创建闭包。我认为这种模式有很大的潜力。

4

7 回答 7

12

要添加有关此主题的注释:

在 JavaScript 中,每当您使用:

  • 函数声明语句或函数定义表达式然后局部变量将具有词法作用域

  • 函数构造函数然后局部变量将引用全局范围(顶级代码)

  • this是 JavaScript 中唯一具有动态范围并通过执行(或调用)上下文设置的内置对象。

因此,要回答您的问题,在 JS 中this,该语言已经是动态范围的功能,您甚至不需要模拟另一种功能。

于 2013-05-10T15:48:53.587 回答
10

属性查找贯穿原型链,它与动态范围非常匹配。只需传递您自己的动态范围变量环境即可使用,而不是使用 Javascript 的词法范围。


// Polyfill for older browsers.  Newer ones already have Object.create.
if (!Object.create) {
  // You don't need to understand this, but
  Object.create = function(proto) {
    // this constructor does nothing,
    function cons() {}
    // and we assign it a prototype,
    cons.prototype = proto;
    // so that the new object has the given proto without any side-effects.
    return new cons();
  };
}

// Define a new class
function dyn() {}
// with a method which returns a copy-on-write clone of the object.
dyn.prototype.cow = function() {
  // An empty object is created with this object as its prototype.  Javascript
  // will follow the prototype chain to read an attribute, but set new values
  // on the new object.
  return Object.create(this);
}

// Given an environment, read x then write to it.
function g(env) {
  console.log(env.x);
  env.x = 2;
}
// Given an environment, write x then call f with a clone.
function f(env) {
  env.x = 3;
  g(env.cow());
}

// Create a new environment.
var env = new dyn();
// env -> {__proto__: dyn.prototype}
// Set a value in it.
env.x = 1;
// env -> {x: 1}  // Still has dyn.prototype, but it's long so I'll leave it out.

f(env.cow());
// f():
//   env -> {__proto__: {x: 1}}  // Called with env = caller's env.cow()
//   > env.x = 3
//   env -> {x: 3, __proto__: {x: 1}}  // New value is set in current object
//   g():
//     env -> {__proto__: {x: 3, __proto__: {x: 1}}}  // caller's env.cow()
//     env.x -> 3  // attribute lookup follows chain of prototypes
//     > env.x = 2
//     env -> {x: 2, __proto__: {x: 3, __proto__: {x: 1}}}

console.log(env.x);
// env -> {x: 1}  // still unchanged!
// env.x -> 1
于 2012-04-08T07:08:54.223 回答
2

我不这么认为。

这不是语言的工作方式。您必须使用变量以外的东西来引用此状态信息。this我猜最“自然”的方式是使用 的属性。

于 2012-04-08T06:34:06.693 回答
2

在您的情况下,与其尝试使用动态范围设置构造函数,不如使用返回值怎么办?

function Class(clazz) {
    return function () {
        clazz.apply(this, arguments).apply(this, arguments);
    };
}

var Rectangle = new Class(function () {
    var width, height;

    this.area = function () {
        return width * height;
    };

    // Constructor
    return function (w, h) {
        width = w;
        height = h;
    };
});

var rectangle = new Rectangle(2, 3);
console.log(rectangle.area());
于 2012-04-08T07:58:35.770 回答
2

为什么没人说this

您可以通过绑定上下文将变量从调用范围传递到被调用函数。

function called_function () {
   console.log(`My env ${this} my args ${arguments}`, this, arguments);
   console.log(`JS Dynamic ? ${this.jsDynamic}`);
}

function calling_function () {
   const env = Object.create(null);
   env.jsDynamic = 'really?';

   ... 

   // no environment
   called_function( 'hey', 50 );

   // passed in environment 
   called_function.bind( env )( 'hey', 50 );

或许值得一提的是,在严格模式下,所有函数都没有默认发送给它们的“环境”(this为 null)。在非严格模式下,全局对象是被this调用函数的默认值。

于 2015-06-12T14:11:47.310 回答
0

如果你有办法做语法糖(例如带有 gensyms 的宏)并且你有 unwind-protect,你可以使用全局变量来模拟动态范围。

宏可以通过将动态变量的值保存在隐藏的词法中然后分配一个新值来重新绑定动态变量。unwind-protect 代码确保无论该块如何终止,都将恢复全局的原始值。

Lisp 伪代码:

(let ((#:hidden-local dynamic-var))
  (unwind-protect
    (progn (setf dynamic-var new-value)
           body of code ...)
    (set dynamic-var #:hidden-local)))

当然,这不是做动态作用域的线程安全方式,但如果你不做线程,它会做!我们会将它隐藏在一个宏后面,例如:

(dlet ((dynamic-var new-value))
   body of code ...)

因此,如果您在 Javascript 中有 unwind-protect 和一个宏预处理器来生成一些语法糖(这样您就不必手动打开所有保存和 unwind-protected 恢复的编码),它可能是可行的。

于 2012-04-08T06:34:23.687 回答
0

我知道这并不能完全回答这个问题,但是要在评论中添加太多代码。

作为一种替代方法,您可能需要查看 ExtJS 的extend函数。这是它的工作原理:

var Rectangle = Ext.extend(Object, {
    constructor: function (w, h) {
        var width = w, height = h;
        this.area = function () {
            return width * height;
        };
    }
});

使用公共属性而不是私有变量:

var Rectangle = Ext.extend(Object, {
    width: 0,
    height: 0,  

    constructor: function (w, h) {
        this.width = w;
        this.height = h;
    },

    area: function () {
        return this.width * this.height;
    }
});
于 2012-04-08T09:27:45.673 回答