this指向undefined uiapp_this为什么会为undefined?
一、前言
普通function定義的函數(shù)
‘運行環(huán)境’也是對象,this指向運行時所在的對象。 如下:
如果一個函數(shù)在全局環(huán)境運行,this就指向頂層對象(瀏覽器中為window對象); 如果一個函數(shù)作為某個對象的方法運行,this就指向那個對象; 如果一個函數(shù)作為構造函數(shù),this指向它的實例對象。箭頭函數(shù)
函數(shù)體內(nèi)的this對象,就是定義時所在的對象,而不是使用時所在的對象。
本來記住這幾點已經(jīng)可以了,this最終找到是可能window,但是undefined是怎么又是怎么來的,本妹子下面將一步步分析。
二、問題點:undefined是怎么來的
綜上所述,this指向運行時所在的對象或指向定義時所在的對象,但是這個對象可能最后找到是window,但都不可能是undefined,那么undefined是怎么來的呢?
<html> <script type="text/javascript"> var foo = function foo() {console.log(this); }; var foo1 = () => {console.log(this); }; foo(); //Window foo1(); //Window </script> </html>三、回答
我們一般寫js文件都是babel轉成ES6的,babel會自動給js文件上加上嚴格模式。
用了嚴格模式"use strict",嚴格模式下無法再意外創(chuàng)建全局變量,所以this不為window而為undefined
<html> <script type="text/javascript"> "use strict"; var foo = function foo(){console.log(this) }; foo();//undefined </script> </html>四、進階問題:嚴格模式對箭頭函數(shù)沒有效果
嚴格模式為什么對箭頭函數(shù)沒有效果,返回還是window?
<html> <script type="text/javascript"> "use strict"; var foo = () => {console.log(this) }; foo(); //Window </script> </html>五、進階問題回答
Given that this comes from the surrounding lexical context, strict mode rules with regard to this are ignored.
lexical means that this refers to the this value of a lexically enclosing function.
綜上所述,在箭頭函數(shù)中,this為lexical類型,lexical意味著這個this指是所在封閉函數(shù)中this,所以嚴格模式會自動忽視use strict,所以this如下所示:
<html> <script type="text/javascript"> var foo = () => {"use strict";console.log(this) }; foo(); //Window </script> </html>箭頭函數(shù)中,this指向運行時所在的對象,而use strict被移到函數(shù)內(nèi)了,所以this為全局變量window。
Happy coding ~~ ^ ^
相關鏈接
this為什么會為undefined??blog.frontendx.cn嚴格模式 - JavaScriptArrow functions - JavaScript
ECMAScript 2015 Language Specification – ECMA-262 6th Edition
函數(shù)的擴展 - ECMAScript 6入門
use strict in javascript not working for fat arrow? - Stack Overflow
總結
以上是生活随笔為你收集整理的this指向undefined uiapp_this为什么会为undefined?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 没有required_springboo
- 下一篇: c# out关键字 vb_在c#中使用o