I am reading this: http://killdream.github.com/blog/2011/10/understanding-javascript-oop/index.html
and i’ve encountered some code that i can’t understand:
function Person(first_name, last_name) {
this.first_name = first_name
this.last_name = last_name
}
// Defines the `name' getter/setter
Object.defineProperty(Person.prototype, 'name', { get: get_full_name
, set: set_full_name
, configurable: true
, enumerable: true })
Why is he using Object.defineProperty on Person.prototype and not simply on Person?
Why not simply include name in the definition or make Person.name = bla...?
(EDIT: SOLVED)
also, why am i seeing this endless loop of prototype reference??

If he’d use
Object.definePropertyonPersonthen you’d define a property on that function and not on the instances you create withnew Person.I.e. given
Object.defineProperty(Person, ...)you were able to dobut that would not really help in this situation.
On the other hand, properties of the prototype are shared by all instances and therefore it makes sense to define this property on the prototype.
Here
Personis a constructor function which is supposed to be called with thenewkeyword. It probably will help to read about whatnewis doing, in order to understand whyPerson.prototypehas to be extended.The gist: When called with
new, inside the function,thiswill refer to an empty object inheriting fromPerson.prototype.Regarding the second part: Each function has a
prototypeproperty, and each prototype has aconstructorproperty referring to its “parent” function. Thus you have a self referencing structure:What you showed is not the prototype chain, which can be revealed by inspecting
__proto__.I could simulate the same with:
and I could access
a.b.a.b.a.b.a.b.a.b.aindefinitely.