Programming on a Jerker PART 6: JavaScript Prototype Gotchas or: How we don’t need no stinkin’ prototypes

Warning: this is a post entirely for those Jerkers, I mean “Jerks”, who program JavaScript at their Ikea desks.

Prototypal JavaScript has two “gotchas” that make complete sense, once you understand what is going on with them. Prototypal sharing of properties can sometimes lead to unexpected results. For instance the variables:
hidden_type.prototype.my_duplicate_var
and
visible_type.my_duplicate_var
these refer to the same value as you can see below.

console.clear();
var hidden_type = function () {};
hidden_type.prototype.my_duplicate_var = 42;
var visible_type = function () {};
visible_type.prototype = Object.create(hidden_type.prototype);
visible_type.prototype.constructor = visible_type;

var visible_obj = new visible_type();
console.log(visible_obj);
hidden_type.prototype.my_duplicate_var = 1066;
console.log(visible_obj);

console.log(hidden_type.prototype.my_duplicate_var);
console.log(visible_obj.my_duplicate_var);

The console output of the above code.

Object { my_duplicate_var=42, constructor=function()}
Object { my_duplicate_var=1066, constructor=function()}
1066
1066

The change from 42 to 1066 can be surprising, but logical, when programming prototypal JavaScript. This cannot happen with classless JavaScript because the objects do not share in a prototypal manner, they are rude.

Here we see what happens when there is more than one property of the same name in prototypal JavaScript. There are two variables called “my_duplicate_var” one is the hidden_type, and one is the visible_type. When the “visible_type.my_duplicate_var” gets deleted it actually doesn’t because JavaScript examines visible_type’s prototype chain and finds the other duplicate: “my_duplicate_var”. There is no prototype chain to refer to in classless JavaScript.

console.clear();
var hidden_type = function () {};
hidden_type.prototype.my_duplicate_var = 42;
var visible_type = function () {};
visible_type.prototype = Object.create(hidden_type.prototype);
visible_type.prototype.constructor = visible_type;

var visible_obj = new visible_type();
visible_obj.my_duplicate_var =8675309;
visible_obj.my_singular_var =Math.PI;

console.log(visible_obj);
delete visible_obj.my_duplicate_var;
delete visible_obj.my_singular_var;
console.log(visible_obj);

The console output of the above code.

Object { my_duplicate_var=8675309, my_singular_var=3.141592653589793, 
 constructor=function()}
Object { my_duplicate_var=42, constructor=function()}

Part 1 2 3 4 5 6 7

Leave a Reply

Your email address will not be published.