當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JS的this
1.作為對象
function person(){this.name="xl";console.log(this);console.log(this.name);}person(); //輸出 window xl 因為本質是window.person() 第一個console 是進行輸出對象window 第二個console 是進行輸出對象window的name屬性 就是x1 var name="xl"; function person(){console.log(this.name); }person(); //輸出 xl?
2.作為方法
例子一: var name="XL";var person={name:"xl",showName:function(){console.log(this.name);} }person.showName(); //輸出 xl//這里是person對象調用showName方法,很顯然this關鍵字是指向person對象的,所以會輸出namevar showNameA=person.showName; showNameA(); //輸出 XL//這里將person.showName方法賦給showNameA變量,此時showNameA變量相當于window對象的一個屬性,因此showNameA()執行的時候相當于window.showNameA(),即window對象調用showNameA這個方法,所以this關鍵字指向window例子2: var personA={name:"xl",showName:function(){console.log(this.name);}} var personB={name:"XL",sayName:personA.showName }personB.sayName(); //輸出 XL //雖然showName方法是在personA這個對象中定義,但是調用的時候卻是在personB這個對象中調用,因此this對象指向跟著最初設定的最前面的對象!!!!!?
總結
- 上一篇: Mysql的IP转换
- 下一篇: JS的parseInt