Javascript this关键字 指向详解
生活随笔
收集整理的這篇文章主要介紹了
Javascript this关键字 指向详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Javascript this關鍵字 指向詳解
面向對象語言中 this 表示當前對象的一個引用。在 JavaScript 中 this 不是固定不變的,它會隨著執行環境的改變而改變。
1) 單獨使用,this 表示全局對象。
<script type="text/javascript">console.log(this) // 指向window全局對象 </script>2) 在方法中,this 表示該方法所屬的對象。
var person = {firstName: "John",lastName : "Doe",id : 5566,fullName : function() {return this.firstName + " " + this.lastName; // 指向person對象} }; person.fullName(); // John Doe3)在函數中,this 表示全局對象。 在嚴格模式下,this 是未定義的(undefined)。
<script type="text/javascript">var q = "hello"var func = function(){var q = 'wang'console.log(this.q) // hello}func() </script> <script type="text/javascript">var q = "hello"var func = function(){var q = 'wang'console.log(this.q) // Cannot read property 'q' of undefined}func() </script>5) 作為構造函數調用 構造函數試圖初始化這個新創建的對象,并將這個對象作為其調用上下文,this 指向這個新創建的對象。
var q = 'window' function Func() {this.q = 'hello'console.log(this.q) //hello } var obj = new Func因箭頭函數沒有this,固不能用作構造函數,否則會報錯
總結
以上是生活随笔為你收集整理的Javascript this关键字 指向详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CENTOS6.4安装vnc-serve
- 下一篇: 小程序 开发经验