简体   繁体   中英

Access inner variables in JavaScript

I am writing a userscript for some site. I need to access inner variable in a function. For example, in following code i need to access "private property" b of object c

function a(){
    var b;
    //assignment to b and other stuff
};
var c=new a();

I CANNOT CHANGE THE SITE'S CODE, I ONLY CAN CHANGE BORWSER EXTENSION SCRIPTISH AND WRITE A USERSCRIPT . My browser is the latest firefox. I need to gain access even if i would have to change Scriptish .

You can't access to your inner variable of your function, you should make it global variable to get it from outside.

var b;
function a(){
 b=1;
    //assignment to b and other stuff
};
var c=new a();
document.write(c.b);

and the output will be 1.

In your code b isn't a private variable, but a local variable. And after execution of var c=new a(); b doesn't exist anymore. Thus, you can't access it.

But if you use closures , everything changes:

function a(){
    var b;
    //assignment to b and other stuff
    this.revealB = function() {
        return b;
    }
};
var c = new a();
alert(c.revealB());

Here b is still a local variable, but its lifetime is affected by closure, thus it's still alive when we call revealB .

It is quite simple thing to do, and it is great for inheritance applications:

You simply return whatever you want, and maybe return it through methods, later reuse it in other functions and build up on it.

Example follows:

    function a(){
        var b;
        //assignment to b and other stuff
        return b;
      };

     // or

   function a(){
        var b, result;
        //assignment to b and other stuff
        returnInitial: function() {
           return b;
         }
        // other stuff with b
        return result;
   };

Later you can use so called "parasitic inheritance" and initiate this whole function inside other function using all local variables and adding new methods, like so:

var a function() {
        var b, result;
        //assignment to b and other stuff
        returnInitial: function() {
           return b;
         }
        // other stuff with b
        return result;
}
var extendedA function() {
    var base = new a;
    var b = a.returnInitial();
    a.addToB = function (c) {
    var sum = c + a.returnInitial();
    return sum;
    }
}

So you can now get

var smt = new extendA();
var c = 12; //some number
var sumBC = extendA.addToB(c);

For all there is to these great practices, I recommend yutube search for doug crockford's lectures on js objects handling.

Note that you need to use new since dynamic object handling which javascript uses can crash your original object if you do not initialize a fresh instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM