javascript - An infinite loop caused because of two getters? -


the following code executes infinite loop (prints getter1 once, , getter2 until stopped):

var person1 = {     _age: 42,     age() {       console.log("getter1");       return this._age;     } };  object.defineproperty(person1, "_age", {     get: function() {       console.log("getter2");       return this._age;   } }); console.log(person1.age); // true 

what causes it? (note: i'm aware fact declared 2 different getters).

it's not infinite loop, infinite recursion. you're return this._age inside getter _age, accessing this._age implicitly calls getter again.

note once you've defined getter called _age old value of _age (42) overwritten. there no property value 42 anymore. if want create getter returns value of property can't getter same property, name getter other _age:

var person1 = {     _age: 42,     age() {       console.log("getter1");       return this._age;     } };  object.defineproperty(person1, "age2", {     get: function() {       console.log("getter2");       return this._age;   } }); console.log(person1.age); // 42 console.log(person1.age2); // 42 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -