PDA

View Full Version : Adding to non-global, non-current scope from current scope?



Trinithis
09-17-2007, 09:05 PM
Is there any way to add to a non-global, non-current scope in Javascript from the current scope?

I want to do something to the effects of:


function a() {
b();
c();
}
function b() {
b.caller.c = function() {
alert("c made from b");
};
}
a();


This doesn't work. Is what I'm trying to accomplish strictly impossible? (Feasibility is not an issue.)

I'm trying to make an Import script that imports code into the scope that called Import(). If I defined Import to return a string, I could do eval(Import("script.js")), but I want to make it so you only have to manually call one function.

boogyman
09-17-2007, 09:28 PM
I believe you could use



function a() {
this.call( b() );
this.call( c() );
}
function b() {
b.caller.c = function() {
alert("c made from b");
};
}
a();


but I may be wrong

Twey
09-18-2007, 07:30 AM
Yup, you're wrong on two counts:
this.call( b() );You want to pass the function b itself to call(), not the return value of the function, so those brackets shouldn't be there. Then, this in that scope refers to the global object. I think you've misunderstood its purpose: it refers to the object as a property of which the function was called, not the function itself. E.G.:
var a = {
b: {
c: function() {
// here, this refers to a.b, not a.b.c.
}
}
};
This doesn't work.No. Adding properties to a function object doesn't create them as variables within the function's scope.
Is what I'm trying to accomplish strictly impossible?As far as I'm aware.
If I defined Import to return a string, I could do eval(Import("script.js")), but I want to make it so you only have to manually call one function.That's ugly. In fact, the original Import() idea was ugly too. The neat solution is to have import() (without a capital, since that's reserved for constructors) return an object, which acts both as a convenient container for the multiple return values and a namespace for the calling function.