What if I want to access actual this variable of a function when it was when created? this can be substituted like in the code below and I need to have a temporary this1 variable in two samples of access. Is it possible not to use temporary variable?
<input id="mybutton" type="button" value="Press Me"/>
<script type="text/javascript">
function Widget() {
var this1 = this;
this.mybutton = $("#mybutton");
this.waspressed = false;
this.onMyButtonPressed1 = function() {
$(this).val("Enough");
this.waspressed = true;
alert("this.waspressed = " + this.waspressed + ", this1.waspressed = " + this1.waspressed);
};
this.onMyButtonPressed2 = function() {
this.mybutton.val("Enough");
this.waspressed = true;
alert("this.waspressed = " + this.waspressed + ", this1.waspressed = " + this1.waspressed);
};
this.mybutton.click( this.onMyButtonPressed1 );
/*
this.mybutton.click( function() {
this1.onMyButtonPressed2();
});
*/
}
$(document).ready(
function() {
a = new Widget();
}
);
</script>
</body>
The
thisvalue is bound on every function call, so if you want to preserve what it was in an enclosing function for use in a nested function the only thing to do is make a copy in a closure variable (like “this1”).To put it another way, you cannot force the runtime system to not bind
thisto something when a function is called.