this scope in javascript
<script type="text/javascript">
var deep_thought = {
the_answer: 42,
ask_question: function () {
return this.the_answer;
}
};
var the_meaning = deep_thought.ask_question();
alert(the_meaning);
</script>
因為this會取最後一個"."之前的物件參考,所以ask_question中的this就是"deep_thought"。所以the_meaning的值為42。
<script type="text/javascript">
function test_this() {
return this;
}
var i_wonder_what_this_is = test_this();
window.answer=100;
alert(i_wonder_what_this_is.answer);
</script>
因為沒有透過new,所以這裡的this代表的是window物件!
<html>
<body>
<script type="text/javascript">
function click_handler() {
window.answer=100;
alert(this.answer); // alerts the window object, show 100
}
function click_handler2() {
window.answer=100;
alert(this.answer); // alerts the button object, show undefined
}
function addhandler() {
document.getElementById('thebutton2').onclick = click_handler;
}
window.onload = addhandler;
</script>
<button id='thebutton' onclick='click_handler()'>Click me!</button>
<br/>
<button id='thebutton2'>Click me2!</button>
<br/>
</body>
</html>
以上因為加入事件的方式不同,所以this也會不同哦!
<script type="text/javascript">
var first_object = {
num: 42
};
var second_object = {
num: 24
};
function multiply(mult) {
return this.num * mult;
}
multiply.call(first_object, 5); // returns 42 * 5
multiply.call(second_object, 5); // returns 24 * 5
multiply.apply(first_object, [5]); // returns 42 * 5
multiply.apply(second_object, [5]); // returns 24 * 5
</script>
使用.call or .apply可以指定function中的this的值。
參考資料:scope in javascript
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^