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(即全局对象)。可以简单理解为避免变量冲突。

相关文章:

  • 2021-12-19
  • 2021-04-22
  • 2021-05-20
  • 2021-04-24
  • 2021-12-03
  • 2021-09-21
  • 2021-09-28
  • 2021-08-29
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-24
  • 2021-08-20
  • 2022-01-19
  • 2022-12-23
相关资源
相似解决方案