JavaScript严格模式下this指向
2017-12-02 16:10
429 查看
一般认为:严格模式下this不允许指向全局对象。是函数体是否处于严格模式!
如:http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html
需要说明的是:本身指向全局的this是没有问题的。
示例代码:
控制台输出为window对象(全局对象):
严格模式下this不允许指向全局对象是指在函数内部,如下示例代码:
控制台输出报错:
补充(2017-12-14):
setTimeout 是window的方法,[b]setTimeout 在调用传入函数的时候,如果这个函数没有指定了的 this,那么它会做一个隐式的操作—-自动地注入全局上下文window[/b]。
与
上述2个代码是相同的。
如: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的方法,[b]setTimeout 在调用传入函数的时候,如果这个函数没有指定了的 this,那么它会做一个隐式的操作—-自动地注入全局上下文window[/b]。
setTimeout(function(){ console.log(111111) },1000)
与
window.setTimeout(function(){ console.log(111111) },1000)
上述2个代码是相同的。
相关文章推荐
- JavaScript严格模式下关于this的几种指向详解
- (function(){}).call(window) 严格模式匿名函数的this指向undefined
- js严格模式下this指向
- JavaScript的变量及函数(变量提升、嵌套作用域、条件语句、严格模式、IIFE、闭包、模块化、this、原型)
- Javascript 严格模式详解 (主要是function的this指针可以为空了!)
- this指向问题——严格、非严格模式,事件处理程序
- Javascript 严格模式详解 (主要是function的this指针可以为空了!)
- 严格模式下禁止 this 指向全局变量
- javascript this指针指向?
- javascript严格模式
- 关于Javascript的严格模式
- javascript中的严格模式
- javascript中的严格模式
- javaScript 中的 this 指向谁
- Javascript 严格模式(strict mode)详解
- 用最简单的方法判断JavaScript中this的指向
- Javascript 严格模式详解
- JavaScript严格模式详解
- 解决iview 中i-table的render方法this指向window(requirejs模式下)
- javascript中的严格模式