Reputation: 105499
I'm exploring some code written for desktop application and it's using ScriptControl
object to access method of a global object (which doesn't require specifying the this
keyword). I'm wondering how this can be done without the usage of ScriptControl. Here is the sample code:
var i = function() {success()};
(function(f) {
var o = {"success": function() {alert('success')}};
f.apply(o); // fails because 'success' method is referenced inside 'f' by itself
})(i);
So is there any way I can access "success" method of parent without specifying the this
keyword?
Upvotes: 0
Views: 63
Reputation: 664513
You can overwrite that global success variable that i references:
var success;
var i = function() {success()};
(function(f) {
// Assuming you have access the the scope where `success` is defined
// which is true for the global scope in this example
success = function() {alert('success')};
f();
})(i);
However, that looks hacky. If you're designing an API, it would be better to pass the callback function as a parameter to i
.
Upvotes: 1
Reputation: 3543
Don't use .apply()
?
var i = function(obj) {obj.success()};
(function(f) {
var o = {"success": function() {alert('success')}};
f(o);
})(i);
Tell you what, here's another way.
var i = function() {i.o.success()};
(function(f) {
var o = {"success": function() {alert('success')}};
f.o = o;
f();
})(i);
Upvotes: 1