dagblog.
← Archive

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 call alert("dagblog".startsWith("xx"));
would return false and alert("dagblog".startsWith("dag"));
would return true. In other words, every string would have a method called startsWith that
it inherits from its prototype.
Suppose we want to describe inheritance between two objects, say Auto and
Škoda. We'd use the prototype property 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, on Objectitself. He also shows how to encapsulate, or hide,
an object's variables.

Medium version

Related articles

Related CZ Podcast episodes