Section 4 - Objects and Functions
Classical vs Prototypal Inheritance
Inheritance when an object gains access to the properties and methods of another object.
Classical Inheritance:
C#, C++
The most popular way its been done.
One approach towards inheritance
Can get clustered.
Prototypal Inheritance:
Flexible, extensible, easily understood.
Achieves the same thing as classical inheritance, but in a different way.
Understanding the Prototype
All objects have a prototype property.
When we reference a property method, the object looks through all the series of the prototypes (the prototype chain), to gain access to a property or method.
proto. methods are hidden directly.
Can have different objects point to different prototype, or any prototype methods.
Its like before, where we've set the 'this' keyword to an object.
.bind(person);
This demonstrates that any object has a prototype method, and even though we dont want to do this, we can redirect it where ever we want.
Note: The reason why getFullName() does not print out default default, as set up in the person object is because of how scope works with prototype methods.
When we set a prototype, it the first object (danny) is on the top of the scope. If it fails the search on the top of this scope, then it begins to search down the prototype chain.
To demonstrate this:
Everything is an Object
(or a primative)
Lets take a look at three basic primitives
In the console of the browser, we can look at these independently with var.proto. , and still a still of inherited functions, and methods.
This demonstrates what is works behinds the scenes in the javascipt engine.
Particular classes of objects have been designated a predetermined set of inheritable definitions.
Reflection and Extend
An object can look at itself, listing and changing its own properties and methods.
To demonstrate extend, lets go back to our two objects
What we've essentially done is print out the defined methods of an object.
This is essentially the same thing as doing:
But without ALL of the methods. But notice how the proto was also defined in there.
To limit the properties to the first object on the top of the scope chain, we can do:
Now, how do we properly inherit in javascript. Turns out their not a formal method in-built (yet; extends() method is coming in the next version).
But for now, we can use the underscore library to suit our needs.
It turns out the _.extend in the underscore.js also overwrites variables defined in the earlier object.
Its use, it seems, would be to when you write independent object methods.
I dont like this as much, because I feel that my extensions should come from one place, and its not defined there, I dont want to inherit from it.
Last updated
Was this helpful?