When we have normal javascript objects, we can access there properties by using a syntax like objectName.proprtyName
. If we just use propertyName
only, then we will get an error as below -
const myObj = {
userIdName : "John"
};
console.log(myObj.userIdName); //John
console.log(userIdName); //error "Not defined"
However, in the case of in-built window
object, we can use both window.propertyName
and propertyName
alone as below -
console.log(window.alert);
console.log(alert);
//both return same result
What exactly is responsible for this behavior of the window
object? Can we replicate the same behavior for any explicitly built object like the object in the first snippet? (Although nobody would want to pollute the global scope, but I just have this query)
Edit - I have received comment that this question is a duplicate of another question. This question is very much similar to my answer except one difference - I am looking for a way to replicate the same globally accessible behavior of the window
object.