On Jun 5, 3:43 am, DanYan <bytecraf...@gm ail.comwrote:
So I was doing some stuff in Javascript, and I want to get access to a
function's scope chain. As a simplified example of what I actually am
trying to do, suppose I have this:
function add(b) {
return function(a) {
return a + b;
};
}
var add3 = add(3);
assert(5 == add3(2));
I want to be able to define a function mul3() that executes in the
same context as bar. I want to do something like this:
function mul3() {
return a * b; // I realize that no b is in static scope here -
see below}
mul3.scope = add3.scope;
assert(6 == mul3(2));
It doesn't appear that functions have a scope property. Is there any
way at all to do this? Is there any theoretically standards-compliant
way to do it? Thanks!
"theoretica lly standards-compliant" would be not using pseudo-
inheritance over closures. I consider it absolutely awful and ugly way
to do things from any OOP point of view, either class-based or
prototype-based. Yet mutable closure-constructors are still in some
fashion - though thanks Gog lesser and lesser - so you may and
probably will disregard this advise.
Fot your question itself you may use call() and apply() methods to get
back into the MCC:
function outer(arg_outer ) {
return function inner(arg_inner , overload) {
if (!!overload) {
arg_outer = overload;
}
return arg_outer + arg_inner;
};
}
var demo = outer(1);
window.alert(de mo(2)); // 3
window.alert(de mo.call(outer,2 ,2)); // 4
window.alert(de mo(2)); // 4