How does an object know about its parent in javascript
Suppose I created a class called Person.
var Person = function(fname){this.fname = fname;};
pObj is an object that I created from this class.
var pObj = new Person('top');
now i add one property to Person class like lname.
Person.prototype.lname = "Thomsom";
now pObj.lname gets me "Thomson".
My question is when pObj doesn't find the lname property in it, how does it know where to look.
a source to share
Every object has a prototype. When the trueti property is not set for an object instance, it is considered in the object's prototype. In Gecko and WebKit, you can use the object property __proto__
to get (or set) a reference to its prototype.
You can get the prototype of an object using the standard myObj.constructor.prototype
a source to share
It has to do with how the JavaScript engine handles links. It will start at the local variable object (associated with the scope) and then "walk" to the prototype chain until it finds it, or reaches the top.
You can read more about this here http://dmitrysoshnikov.com/ecmascript/chapter-4-scope-chain/
a source to share
Each object has an internal property, known as [[Prototype]]
, which contains a reference to another object, known as its prototype. When the JS interpreter cannot find a named property in its own object objects, it looks for them in the object prototype, prototype prototype, and so on, until it reaches Object.prototype
the lowest prototype of each object that has no [[Prototype]]
.
The property is [[Prototype]]
assigned the value of the property of the function constructor by the prototype
operator new
. So when you call new Person
, a new object gets [[Prototype]]= Person.prototype
. When you create a function, it gets a new empty object for its property prototype
, but you can completely reassign the constructor function .prototype
and also write new members to it.
However, the property [[Prototype]]
remains unchanged throughout the life of the object; in particular, while adding new members to Person.prototype
makes them visible in all instances Person
, assigning a new object Person.prototype
does not change the prototypes of existing instances Person
.
Usually [[Prototype]]
an invisible implementation detail. But in Mozilla, the internal property [[Prototype]]
appears under the public property __proto__
. This non-standard extension was accepted by Opera, Safari and Chrome, but not IE. In general, this is considered a bad form to rely on.
In ECMAScript Fifth Edition, you can get the value [[Prototype]]
using a new function Object.getPrototypeOf(person)
. Browser support is still low.
a source to share
The class Person
has prototype
, which is the inheritance chain for instances of type Person. Since this prototype has a property lname
, any instance of type Person, such as pObj
, will use the corresponding value, unless the instance has overridden, for example, in pObj.lname = "Johnson"
.
a source to share