Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit way to check whether a function was called from within the Window

Tags:

javascript

Is there a more explicit way of checking whether a function was called from within Window than if (typeof this.value == "undefined") in the code below?

So that it is apparent that I am checking against Window, something like: 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>
like image 340
barciewicz Avatar asked Feb 24 '19 08:02

barciewicz


2 Answers

Just check if this is 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>
like image 177
Snow Avatar answered Sep 22 '22 07:09

Snow


You can check if this==window or if strict mode is on check if this is 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>
like image 26
Vikas Yadav Avatar answered Sep 18 '22 07:09

Vikas Yadav