如果我想在创建函数时访问函数的实际this
变量,该怎么办? this
可以替换为下面的代码,我需要在两个访问样本中有一个临时this1
变量。是否可以不使用临时变量?
<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>
答案 0 :(得分:1)
this
值绑定在每个函数调用上,因此如果要保留封闭函数中的内容以便在嵌套函数中使用,唯一要做的就是在闭包变量中复制(比如“this1”)。
换句话说,当调用函数时,您无法强制运行时系统不绑定this
。