3 回答

TA贡献1995条经验 获得超2个赞
属性查找贯穿整个原型链,该原型链与动态范围非常匹配。只需传递您自己的动态范围变量环境即可使用,而不是使用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

TA贡献1779条经验 获得超6个赞
要添加关于此主题的注释:
在JavaScript中,只要您使用以下内容:
函数声明语句或函数定义表达式,则局部变量将具有词法范围。
函数构造函数,然后局部变量将引用全局范围(顶级代码)
this
是JavaScript中唯一具有动态作用域并通过执行(或调用)上下文设置的内置对象。
因此,要回答您的问题,在JS中this
,该语言已经是动态作用域的功能,您甚至无需模仿其他功能。

TA贡献1828条经验 获得超4个赞
为什么没有人说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调用函数的默认值。
添加回答
举报