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>
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With