开发者

Access private (local) variable inside a closure scope

I'm making a google chrome extension and trying to get reference of a local variable within a closure scope.

// The script model of the target website
// I can't change any code of these
function Player(playerName){
    this.name = playerName;
    this.score = 0;
}

function Match(playerRed,playerBlue){
    var player_red = new Player(playerRed);
    var player_blue = new Player(playerBlue);
}

var tennis = new Match("Mike","John")

so what I'm trying to do in my content script is to inject a function into prototype of Match just to get the variable player_red and player_blue:

function Match(playerRed,playerBlue){
    var player_red = new Player(playerRed);
    var player_blue = new Player(playerBlue);

    //hoping to add this into Match.prototype
    this.showMatchInfo = function(){
            alert(player_red.name + " vs " + player_blue.name);
    }
}

but this will not work because player_red and player_blue isn't defined under this.

I fou开发者_开发问答nd this question through search. The solution is to "wrap the constructor in a new constructor and then set the prototypes equal". Unfortunately this doesn't work for me as I have no access to the original script of the website and probably because:

  • even by create new myMatch, the new myMatch doesn't not inherit the player_red and player_blue variable from their original Match instance.
  • Are there any possible workarounds? Thanks.


Notes on "partial solution":

Please note that the code snippets posted below only show "some alternatives which may or may not provide enough to get by". This is because they don't capture the values (Player objects) within the constructor, but only wrap the values going inside.

A "full solution" might also wrap the Player constructor and use a property or other mechanism to "remember" the objects created for different input values; alternatively, it could remember object creation order. This could then be used to wrap Match and then extract the created Players from the shared store after the Match constructor had run -- those details, however, are left as an exercise. The Player wrapping code can utilize the code presented below (assuming Player is a global/accessible property).


The exact request is not possible given the above context.

Variables (real variables, not properties) can only be accessed from the scope they are declared in or a nested scope as they are resolved through scope chains. This also includes usage of eval. While this may seem like a limitation, it also ensures that scope chains (and their variables) can't be externally mucked with unless exposed.

However, consider this fun approach, which utilizes the fact that an explicit object can be returned from a Constructor:

var oldMatch = Match
// note this form, else above would be pre-clobbered
Match = function Match (playerRed, playerBlue) {
    var m = new oldMatch(playerRed, playerBlue)
    // either "inject" method here, or save in object for later
    m.myPlayerRed = playerRed
    m.myPlayerBlue = playerBlue
    return m
}

Of course, this will break things like new Match(...) instanceof Match.

Happy coding.


Update:

Here is a modification of the above to work with the "wrap the constructor in a new constructor and then set the prototypes equal" method as discussed in the link in the post. The trick is "stealing" the global properties name. I have also altered the code to keep oldMatch "private" to avoid pollution.

// note this form, else Match property would be pre-clobbered
Match = (function (oldMatch) {
    function Match (playerRed, playerBlue) {
        oldMatch.call(this, playerRed, playerBlue);
        // either "inject" method here, or save in object for later
        this.myPlayerRed = playerRed
        this.myPlayerBlue = playerBlue
    }
    Match.prototype = oldMatch.prototype
    return Match
})(Match)

Unlike the first code snippet, this should work with new Match(...) instanceof Match, but it may still break depending upon particular assumptions made within the Match object methods.


Example of how to invert ("extract") data from Player constructor:

// original -- remember this method will only work
// if Player is used as a property (and not itself a closure'd variable)
function Player (name) {
    this.name = name
}

Player = (function (oldPlayer) {
    function Player (name) {
        oldPlayer.call(this, name)
        var fn = arguments.callee
        fn.recent = fn.recent || []
        fn.recent.push([name, this])         
    }
    Player.prototype = oldPlayer.prototype
    return Player
})(Player)

var p1 = new Player("fred");
var p2 = new Player("barney");

alert("instanceof check? " + p1 instanceof Player)
alert("name check? " + ("barney" == p2.name))

alert(Player.recent.join(","))
Player.recent = [] // reset
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜