While playing around with a simple Javascript Object Initializer example, I could not find an explanation while the following code:
const obj = {
self: this
};
console.log(obj);
would lead an Error: Maximum call stack size exceeded?
Meanwhile, a slightly different but may look similar initializer block as follows:
const obj = {
self: obj
};
console.log(obj);
would lead an Error: Cannot access uninitialized variable. while the following example using method initializers works perfectly fine:
const obj = {
name: 'Bob',
a() {
return obj.name;
},
b() {
return this.name;
},
};
console.log(obj.a());
console.log(obj.b());
Can you elaborate on the object initialization process and why the language allows the under initialization object and its this references usage inside method initializers and not in property values?
Case 1
this === globalHere
thisis the global javascript context. Typically is huge and contains many circular references. When youconsole.log()an object with circular references the outcome depends on the implementation (it does not throw an error onChrome 93.0.4577.63).See what is
globalThis.See how to print a circular reference.
Case 2
obj is undefinedThis is invalid syntax. First the expression
{ self: obj }will be evaluated, then the assignment will be performed. But when the expression is evaluatedobjdoes not exist hence leads toError: Cannot access uninitialized variable..This will do what you expect:
Case 3
The last example is not related to the other examples at all.
objfroma()at a deferred time, soconst obj =has already been performed.This function will lead to the errors you see above: