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.
What exactly is responsible for this behavior of the
window
object?
JavaScript has two major types of environment records (a construct to "hold" name -> value associations): a declarative record and an object record.
A declarative environment record stores those association in an implementation specific manner. This is the most common type of environment record and is created when you call a function for example.
An object environment record uses, as indicated by the name, an actual JavaScript object as the "backend". That means every entry in that environment becomes a property of that "binding object" and vice versa.
The global environment uses such an object environment and that binding object is available via window
in browsers.
Can we replicate the same behavior for any explicitly built object like the object in the first snippet?
It is possible with the deprecated with
statement still exists and creates an object environment record using the provided object as a binding object. From the spec:
The
with
statement adds an object Environment Record for a computed object to the lexical environment of the running execution context. It then executes a statement using this augmented lexical environment. Finally, it restores the original lexical environment.
var obj = {foo: 42};
with (obj) {
console.log(foo);
}