Tuesday, July 5, 2011

Apple JavaScript Coding Guidelines - Issue with Recommended "Inheritance" Use

Today at work, one of the devs pointed to this "Apple JavaScript Coding Guidelines" document and expressed some concerns about some of their tips.

> http://developer.apple.com/library/mac/documentation/ScriptingAutomation/Conceptual/JSCodingGuide/JSCodingGuide.pdf

I was reading though it I came to the bit about "Inheritance" which is explained as below:

"JavaScript allows an object to inherit from other objects via the prototype keyword. To inherit from another object, set your object’s prototype equal to the prototype of the parent object, like this:

MyChildObject.prototype = MyParentObject.prototype;

This copies all of the parent’s functions and variables to your object. It does not, however, copy the default values stored in that object.... "

Now there is a major flaw with this, as setting "MyChildObject.prototype = MyParentObject.prototype" will not only copy all the parents functions to the child every time the parent is extended with prototype, but it will also copy all the child's functions to the parent as well, which is NOT real inheritance.

Here is some code that proves its incorrect:

parentPerson = function() {
  this.name = "";
  this.sayName = function() {

childPerson = function() {
  this.name = "";
  this.sayName = function() {

childPerson.prototype = parentPerson.prototype;

parentPerson.prototype.sayPoliteName = function() {
  alert('Pleased to meet you ' + this.name);

childPerson.prototype.sayRudeName = function() {
  alert('You are full of crap ' + this.name);

var newParent = new parentPerson();
newParent.name = "Mark";
newParent.sayRudeName(); // should NOT be work but does

var newChild = new childPerson();
newChild.name = "Paul";

Test and Fiddle with this code on jsfiddle

So, as you can see this is not a good recommendation by Apple. What do you guys think?

1 comment:

  1. This comment has been removed by a blog administrator.


Fork me on GitHub