Sett scope on javascript function call
I want to call a javascript function within a protected scope and i can do it this way
var a = "Global a";
( function() {
var a = "Local a";
var alertA = function() {
alert(a);
}
alertA();
})();
This alerts "Local a" butt what i realy would like to do is to get the same result with an already declared function.
var a = "Global开发者_如何转开发 a";
var alertA = function() {
alert(a);
}
( function() {
var a = "Local a";
alertA();
})();
So my question is how can a call alertA with a different scope so the result would be "Local a"
The reason i would like to do this i want to call globally defined functions on different iframes and have global variabels like document and window point to the appropriate documents and windows for every specific iframe.
Let me put it as an answer:
I suggest you make the function accept window
and document
as argument:
function someFunc(window, document, otherParameter) {
}
In each frame, you can then take its window
and document
as pass it to the function. For convenience, you can create a wrapper function in each frame, which does this for you:
var localSomeFun = function() {
return someFun.apply(null, [window, document].concat(arguments));
}
use the following:
var a = "Global a";
var alertA = function () {
alert(a);
}
(function () {
var a = "Local a";
alertA.apply(window, []);
})();
I guess you will have to refactor your code a bit, I enclose my solution:
var a = "Global a",
alertA = function() {
console.log(this.a);
};
alertA();
(function() {
var context = {};
context.a = "Local a";
alertA.call(context);
})();
You will have to store all variables in a specialized context
object. Inside a function you will need to use this.%variable_name%
instead of plain %variable_name%
.
精彩评论