Scope inside a prototyped function?

Giganews Newsgroups
Subject: Scope inside a prototyped function?
Posted by:  BrianMH (bmhero…@gmail.com)
Date: 8 Sep 2006

I'm trying to access some of the global's inside my class LiveSearch
and I have no idea how to go about it.  Here is what I have so far:

<script type="text/javascript" src="query.js"></script>
<script type="text/javascript">
function LiveSearch(global) {
    this.theglobal = global;
    this.initialize();
}

LiveSearch.prototype.initialize = function() {
    $("#thebutton").mousedown(function() { //when we click the button
        alert(this.theglobal);
    });
}

$(document).ready(function() {
    var objSearch = new LiveSearch("globalvalue");
});
</script>

On page load I create a new LiveSearch instance and it assigns
theGlobal = "globalvalue" and proceeds to initialize();  At this point
Im using JQuery to setup an onmousedown event on a button on my page
with id="thebutton". When I click the button the alert comes back with
'undefined'. How can I get direct access to my theglobal variable?

The only way I have found so far is by adding a local variable to my
initialize() func and alerting the local variable:

LiveSearch.prototype.initialize = function() {
        var theglobal = this.theglobal;
    $("#thebutton").mousedown(function() { //when we click the button
        alert(theglobal);
    });
}

Now this works fine, but Im only accessing a local copy of theglobal,
so I cannot alter its value. (setting theglobal = "somethingelse"; only
alters my local copy, not the one specified in my class constructor).
Is there a way to do this?

The answer is probably all to obvious, but Im beating my head against a
wall here trying to come up with the answer - thanks ahead of time guys!

Replies