为什么要使用func.call(this)
2024-09-06 23:16:37
1.为什么要使用func.call(this)
在正常模式下,js 函数里那些你没有声明就使用的变量,其实是访问的全局对象的属性。但是在严格模式下,不允许这种语法,所有变量都必须要显示声明,所以如果你不用 call() 传递 this 给这个函数,那么就会报错了。用了严格模式,就必须这么写。
(function(){
console.log(this === window) // true
})();
(function(){
console.log(this === window) // true
}).call(this); /* 严格模式 */
(function(){
'use strict'
console.log(this === window) // false
})();
(function(){
'use strict'
console.log(this === window) // true
}).call(this);
严格模式下函数调用this不会默认指向全局对象,使用func.call(this)确保函数调用的this指向函数调用时的this(即全局对象)。可以简单理解为避免变量冲突。
最新文章
- php mysqli mysqli_query() mysqli_real_query()
- js获取文档高度
- JS中的 new 操作符简单理解
- 【spring bean】 spring中bean之间的引用以及内部bean
- iOS:一些常用的框架
- vim - Highlight unwanted spaces
- HTML5 新特性总结
- ADS(一)
- Hark的数据结构与算法练习之Bogo排序
- hostapd and wpa_supplicant
- Add, remove, shuffle and sort
- ThinkPHP的配置
- Spring-----9、容器中bean的生命周期
- MailTest
- 【爬虫入门01】我第一只由Reuests和BeautifulSoup4供养的Spider
- C# 循环时,操作另外一个进程直到操作完成,循环继续执行
- Notepad2用法说明
- ACM-ICPC 2018 焦作赛区网络预赛 I Save the Room
- node-disconf-client基本配置
- 【BZOJ】【3653】谈笑风生
热门文章
- 常用的MySQL语句写法
- 分享知识-快乐自己:快速理解(Java内部类)
- 机器学习(二十四)— 偏差Bias 与方差Variance
- Hibernate学习---第十节:Hibernate之QBC、样例查询&;离线查询
- LSM Tree 学习笔记——本质是将随机的写放在内存里形成有序的小memtable,然后定期合并成大的table flush到磁盘
- Appium-appium日志分析
- java_面试_02_Java面试题库及答案解析
- Linux-tcpdump command
- codeforces 632A A. Grandma Laura and Apples(暴力)
- 洛谷【P3379】【模板】最近公共祖先(LCA)