I walked on something weird while doing some JS code today.
I wanted to execute an object's method if the property existed, and some other function if it didn't. Feeling a little bit fancy, I wrote something like:
var obj = {
method: function(){
console.log(this);
}
}
(obj.method || some_other_function)();
This executes obj.method
if it exists, and some_other_function
otherwise.
But the this
keyword refers to the window
Object when obj.method is executed, and I have absolutely no idea why.
Note that executing (obj.method)();
gives the expected result (this referring to my object)
Obviously I don't need this syntax to make my code run, but I really wonder what's happening here.
I couldn't find any answer either here or elsewhere, the closest thing I found is this interesting post, but it doesn't cover this specific case.
Anyone knows what's happening there?
here is a fiddle showing the thing in action!