Java Script Prototype Visualized
Java Script Prototype Visualized
come and bite me if you still don’t understand the concept of prototype after
this presentation
PROTOTYPE OF FUNCTION
Every function is born with a prototype object, it’s used as the shared prototype(parent) of the
objects created by this function( invoked as constructor function).
The prototype is initially an empty object, you can add members to it. Such all its “children” have
access to these members( properties, methods ) as well.
proto
WHAT’S THE RELATIONSHIP?
F
? proto
prototyp constructo
e r
CONSTRUCT A NEW OBJECT
let’s walk through the following simple code to understand the whole process
this.age = age;
name: Bob
}; age: 18
there’re 3 steps are done by the javascript engine whenever a new instance is
created, let’s see them in action.
built-
in
F Object
ne
w
prototyp constructo prototyp constructo
e r e r
proto
anObjec
t
RESOLVE PROPERTY
let’s see how javascript engine resolve
var value = anObject.someProperty; property lookup
built-
in
Lookup “someProperty” on F2 F1 Object
anObject
1
prototyp constructo prototyp constructo prototyp constructo
e r e r e r
somePropert somePropert
y y
Inheritance
prototyp
e r
prototyp constructo
F
prototyp constructo
e r e r
new prototyp
e
proto
let’s look at a frequent mistake of doing classical Why is the first example is wrong ? Well, I
wouldn’t say it’s always wrong, but in most
Developer Person cases, it’s wrong. Because the subclass
new
Developer’s prototype is an
prototyp constructo prototyp constructo
instance of Person Class, that means it’s a
e r e r Wrong special individual person. And in most
proto case, the Person Constructor would
require some arguments to initialize a
Person instance, such as: name, age … Do
we want these properties on the prototype
Developer Person of Developer ? No ! What we want is a bare
object which just has a “ proto ” points
F to the prototype of Person Class. That’s
prototyp constructo prototyp constructo correc
e r e r exactly how the second example does.
new prototyp t Through a temporary constructor function
e
proto F which does nothing in its constructor, it
will create a bare object points to the
prototype of F which is equal to prototype
OBJECT.CREATE
built- built-
in in
Fu nction Object
proto
proto proto
F function
Empty(){}
ne
w
prototyp constructo
e r proto
proto
JAVASCRIPT OBJECT LAYOUT