JavaScript嚴格模式下this指向


一般認為:嚴格模式下this不允許指向全局對象。是函數體是否處於嚴格模式!

如:http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html

 

需要說明的是:本身指向全局的this是沒有問題的

示例代碼:

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>嚴格模式下this指向</title>
    </head>

    <body>
        <script type="text/javascript">
            'use strict'; console.log(this); </script>
    </body>

</html>

控制台輸出為window對象(全局對象)

嚴格模式下this不允許指向全局對象是指在函數內部,如下示例代碼:

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>嚴格模式下this指向</title>
    </head>

    <body>
        <script type="text/javascript">
            'use strict'; function F() {     this.a = 1;   //這種指向全局的this不對
 }; F(); </script>
    </body>

</html>

控制台輸出報錯:

 

補充(2017-12-14):

"use strict"; (function(){ console.log(this)//undefined
})(); !function(){ console.log(this)//undefined
}(); setTimeout(function(){ console.log(this) //window
},0); function a(){ console.log(this); } a(); //undefined

setTimeout 是window的方法,setTimeout 在調用傳入函數的時候,如果這個函數沒有指定了的 this,那么它會做一個隱式的操作—-自動地注入全局上下文window

setTimeout(function(){ console.log(111111) },1000)

window.setTimeout(function(){ console.log(111111) },1000)

上述2個代碼是相同的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM