How to pass external variables to a private javascript outer closure function?
I may have made some poor design choices on this one. I have several objects being instanced like this.
core.modules.trial = function(sandbox){
return{
alert_private : function(){
alert(omgpi);
}
};
};
I would like to do this:
core.modules.trial[omgpi] = "external private var";
var trial = core.modules.trial();
trial.alert_private(开发者_如何学运维); //would hopefully output "external private var"
I am trying to assign the omgpi variable to the private scope of the outer function. Normally you would do var omgpi within the outer function before returning anything. But I am trying to do this from an external script when this function is called
You can monkey-patch core.modules.trial:
var old_constructor = core.modules.trial;
core.modules.trial = function(sandbox) {
this.omgpi = 'whatever'; // or an object you can add to as desired
return old_constructor.call(this, sandbox); // rebinds to this this
};
See the documentation for call.
Is this what you want?
core.modules.trial = function(sandbox){
var c = arguments.callee;
return{
alert_private : function(){
alert(c.omgpi);
}
};
};
core.modules.trial = function(sandbox){
var self = {
alert_private: function(){
alert(self.omgpi);
}
};
return self;
};
If you need omgpi to be in the closure, you need to set it from within. You can't set things in closures you're not a part of.
core.modules.trial = function(sandbox){
///////////////////////////
var omgpi = this.omgpi;
///////////////////////////
return{
alert_private : function(){
alert(omgpi);
}
};
};
But whenever you call core.modules.trial(), this
refers to modules because that's like the parent. So you could stick the value in modules like this:
core.modules.omgpi = "external private var";
Then the rest works:
var trial = core.modules.trial();
trial.alert_private(); // alerts "external private var"
By the way, your original code had a bug:
core.modules.trial[omgpi]
This uses the value of the variable omgpi as the key. You want either core.modules.trial.omgpi
or core.modules.trial["omgpi"]
.
精彩评论