0

Say I'm writing a greasemonkey/chrome extension script that needs access to a variable that's inside of a closured anonymous method, like so

$(document).ready(function() {
    var goldenTreasure = "Tasty Loins";
}

is there anyway I can get to that goldenTreasure and have me some tasty loins?

note: I can't edit the above method, it's on a site, and my extension needs access to the treasure inside.

3 Answers 3

1

There is no way to access a var that's inside a closure as it is a private variable that is technically hidden inside the containing closure. Only functions inside that closure may have access to it.

Sign up to request clarification or add additional context in comments.

2 Comments

thank's for your help, check the clarification in my question now. the code is pre-existing on a site, and I'm just trying to get to the treasure inside with my injected script
@vvMINOvv There is no way to access those loins for you unfortunately :P
0

You can declare a variable outside of the anonymous function and just assign the one inside as its value. (do it this way if you plan to reuse goldenTreasure for another purpose inside the anonymous function.

var some;

$(document).ready(function() {
    var goldenTreasure = "Tasty Loins";
    some = goldenTreasure;
}

1 Comment

thank's for your help, check the clarification in my question now. the code is pre-existing on a site, and I'm just trying to get to the treasure inside with my injected script
0

Define the variable outside, then assign value inside.

var goldenTreasure;

$(document).ready(function() {
    goldenTreasure = "Tasty Loins";
}

Or another way of doing it is to assign it as a property of the window object

$(document).ready(function() {
    window.goldenTreasure = "Tasty Loins";
}

1 Comment

thank's for your help, check the clarification in my question now. the code is pre-existing on a site, and I'm just trying to get to the treasure inside with my injected script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.