An easier way to work with JavaScript objects
JavaScript is an object-oriented programming language. It uses
what's known as prototypal inheritance to express parent-child relationships. Each object is
created from a template called a prototype. An instance gets all its methods and properties
from that template, which is what gives prototypal inheritance its name.
Objects inherit from their prototypes.
You assign a property or a method through the prototype
property of the object in question. Suppose we want to add a method to String that returns
a Boolean value ( true|false), depending on whether the string
starts with a given prefix. Here's how to do that with prototypal inheritance.
String.prototype.startsWith = startsWith;function startsWith(prefix){
len = prefix.length;
foo = this.substring(0,len);
return (foo == prefix);
}With this in place, the callalert("dagblog".startsWith("xx"));
would returnfalseandalert("dagblog".startsWith("dag"));
would returntrue. In other words, every string would have a method calledstartsWiththat
it inherits from its prototype.
Suppose we want to describe inheritance between two objects, say Auto and
Škoda. We'd use theprototypeproperty to give
Škoda all the properties of Auto that we want it to inherit.
That's my quick look at how JavaScript objects work. In his article Rethinking JavaScript Objects
, Nicholas C. Zakas shows a much easier way to handle parent-child inheritance,
right at the root of all objects, onObjectitself. He also shows how to encapsulate, or hide,
an object's variables.
Related articles
Related CZ Podcast episodes
- #217 · Ivo Lukačovič
On Windy, JavaScript and building companies. · Czech audio
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio