After many hours looking for a explanation and failing, I am asking it here.
All code here are examples made from what I was working on.
Simple object:
let obj = {
fun: window.getComputedStyle,
ele: $('#myDiv')[0]
};
When trying the following function call:
obj.fun(obj.ele);
Gives the following error:
Uncaught TypeError: 'getComputedStyle' called on an object that does not implement interface Window.
I am using jQuery to retrieve the JS element, but using document.getElementById
would produce the same result.
I did search for a while about different types of objects, and found this style:
let obj = {
fun: function() {return window.getComputedStyle},
ele: $('#myDiv')[0]
};
But this type needs to be called differently:
obj.fun()(obj.ele);
This approach works correctly.
Obviously the expanded version of the code works as intended:
window.getComputedStyle($('#myDiv')[0]);
The above code returns the full object correctly.
So my questions are:
Thank you!
When you call the obj.fun()
-method you are calling getComputedStyle
with the scope obj (this value)
and not with the global scope (this/window/globalThis).
There are several way to fix this particular behaviour:
You can make use of a function, such as arrow functions and define fun-property
as following:
fun: (e) => window.getComputedStyle(e)
See a working snippet below:
let obj = {
fun: (e) => window.getComputedStyle(e),
ele: $('#myDiv')[0]
};
console.log(obj.fun(obj.ele));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv"></div>
You can make use of Function.prototype.bind to access the correct context on function invokation using this code:
fun: window.getComputedStyle.bind(this)
See a working snippet:
let obj = {
fun: window.getComputedStyle.bind(this),
ele: $('#myDiv')[0]
};
console.log(obj.fun(obj.ele));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv"></div>