检查是否从Window内部调用函数的显式方法

时间:2019-02-24 08:20:58

标签: javascript

是否有比if (typeof this.value == "undefined")更明确的方法来检查是否从Window内部调用了函数 在下面的代码中?

很明显,我正在对Window进行检查,例如:if this.name === "Window"

function get_caller() {
  if (typeof this.value == "undefined") {
    console.log('function get_caller called from window')
  }
  else {
    console.log('function get_caller called by button press')
  }
}

btn.addEventListener('click', get_caller)
get_caller()
<button id="btn">Get caller</button>

2 个答案:

答案 0 :(得分:8)

只需检查this是否为window

function get_caller() {
  if (this === window) {
    console.log('function get_caller called from window')
  }
  else {
    console.log('function get_caller called by button press')
  }
}

btn.addEventListener('click', get_caller)
get_caller()
<button id="btn">Get caller</button>

答案 1 :(得分:1)

您可以检查是否this==window或是否处于严格模式下,检查this是否为undefined

function get_caller() {
"use strict";    // !this is used for strict mode check
 if (this == window || !this) {
    console.log('function get_caller called from window')
  }
  else {
    console.log('function get_caller called by button press')
  }
}

btn.addEventListener('click', get_caller)
get_caller()
<button id="btn">Get caller</button>