3 回答

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
屬性查找貫穿整個(gè)原型鏈,該原型鏈與動(dòng)態(tài)范圍非常匹配。只需傳遞您自己的動(dòng)態(tài)范圍變量環(huán)境即可使用,而不是使用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貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
要添加關(guān)于此主題的注釋:
在JavaScript中,只要您使用以下內(nèi)容:
函數(shù)聲明語句或函數(shù)定義表達(dá)式,則局部變量將具有詞法范圍。
函數(shù)構(gòu)造函數(shù),然后局部變量將引用全局范圍(頂級代碼)
this
是JavaScript中唯一具有動(dòng)態(tài)作用域并通過執(zhí)行(或調(diào)用)上下文設(shè)置的內(nèi)置對象。
因此,要回答您的問題,在JS中this
,該語言已經(jīng)是動(dòng)態(tài)作用域的功能,您甚至無需模仿其他功能。

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
為什么沒有人說this?
您可以通過將變量綁定到上下文來將變量從調(diào)用范圍傳遞到被調(diào)用函數(shù)中。
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 );
也許值得一提的是,在嚴(yán)格模式下,默認(rèn)情況下,所有函數(shù)都不會(huì)發(fā)送“環(huán)境”(this為null)。在非嚴(yán)格模式下,全局對象是被this調(diào)用函數(shù)的默認(rèn)值。
添加回答
舉報(bào)