Crockford's JavaScript OOP system

P

Peter Michaux

Douglas Crockford doesn't seem to like JavaScript's built-in syntax
for building new objects based on a prototype object. The constructor
function, its prototype property and the "new" keyword all seem very
offensive to him. For over a year, Crockford has proposed an alternate
way of using prototypes like this

function object(o) {
function F() {}
F.prototype = o;
return new F();
}
var newObject = object(oldObject);

I can see some appeal in Crockford's technique above. I do see some
inefficiency in the code above as the little dance with F() and its
prototype needs to occur for every object created.

What concerns me more is his suggested use in the above link of
object() function in combination with what he calls "maker functions"
and "parasitic inheritance".

-------

When I first watched Crockford speak about parasitic inheritance it
took something similar to the following form where person() and
employee() are maker functions.

function person(first) {
return {
first: first,
getName: function() {
return this.first;
}
};
}

function employee(first, position) {
var that = person(first);
that.position = position;
that.getPosition = function () {
return this.position;
};
return that;
}

var giselle = employee("Giselle", "hot model");
giselle.getName();

The above code is inefficient as the functions objects referenced by
the getName and getPosition are not shared by all employee objects.
This leads to triple memory use compared with a standard JavaScript
formulation using a function as a constructor with the getName and
getPosition functions as properties of the constructor's prototype.

-------

Now Crockford is recommending his prototypal system with the object()
function in combination with parasitic inheritance. I haven't seen
clear examples where he is augmenting functions in the "prototype
object chain". It seems he has used parasitic inheritance more for
augmenting non-function valued properties: building up a hash. I am
not clear how Crockford would implement his recommendation with
multiple levels of makers where functions are augmented but he does
mention "secret" variables and privileged function properties. This
seems to lead in the direction of inefficiencies of the parasitic
example above where the privilaged function objects cannot be shared.

------

A while ago I played with using prototypes a different way than I
normally do to really emphasis the building up of complete prototype
objects. Below is my thinking translated to use Crockford's object()
function. In this way the getName and getPosition functions are shared
in memory.

function object(o) {
function F() {}
F.prototype = o;
return new F();
}

// build up a prototypical person
var adam = {
first: 'Adam',
getName: function() {
return this.first;
}
}

// a person maker function
function person(first) {
var p = object(adam);
p.first = first;
return p;
}

// build up a prototypical employee
var homer = person('homer');
homer.position = 'safety';
homer.getPosition = function() {
return this.position;
}

// an employee maker function
function employee(first, position) {
var e = object(homer);
e.first = first;
e.position = position;
return e;
}

var giselle = employee("Giselle", "hot model");
giselle.getName();

---------

The above example could easily be written in the normal JavaScript way
without the need for the object() function.

var adam = {
first: 'Adam',
getName: function() {
return this.first;
}
}

function Person(first) {
this.first = first;
}
Person.prototype = adam;

var homer = new Person('homer');
homer.position = 'safety';
homer.getPosition = function() {
return this.position;
}

function Employee(first, position) {
this.first = first;
this.position = position;
}
Employee.prototype = homer;

var giselle = new Employee("Giselle", "hot model");
giselle.getName();


It seems to me that this last example is quite similar to the previous
example. This example is, in fact, more declarative than the previous
example because in this last example there are lines like
"Person.prototype = adam;" which says what it means quite clearly.
This example is also more efficient (although perhaps just slightly)
without the need for the "F() dance" in object(). This example uses
language-level constructs which which JavaScript programmers are
familiar. Even disregarding the object() function's length, this
example is shorter.

-------

Do you see advantages to using Crockford's object() function?

Do you see the apparent ugliness that Crockford seems to see in the
JavaScript built-in system of constructor functions, their prototype
objects and the "new" keyword?

Is there precedence for Crockford's object() function from another
language?

Should the JavaScript language have an facility like Crockford's?
object() function?

How would you code this Person-Employee example?

If you happen to be Douglas Crockford, how badly have I misinterpreted
your writing and speaking?

======================================================

REFERENCES

Crockford's page containing the object() function
<URL: http://javascript.crockford.com/prototypal.html>

Crockford's page mentioning parasitic inheritance
<URL: http://javascript.crockford.com/inheritance.html>

Crockford videos mentioning parasitic inheritance
See the "Advanced JavaScript" series on YUI blog
<URL: http://developer.yahoo.com/yui/theater/>

JSLint
<URL: http://jslint.com>

Crockford's Top Down Operator Precedence article
Precursor to his chapter in "Beautiful Code"?
<URL: http://javascript.crockford.com/tdop/tdop.html>
 
R

Richard Cornford

Peter said:
Douglas Crockford doesn't seem to like JavaScript's built-in
syntax for building new objects based on a prototype object.
The constructor function, its prototype property and the
"new" keyword all seem very offensive to him.
For over a year, Crockford has proposed an alternate
way of using prototypes like this

function object(o) {
function F() {}
F.prototype = o;
return new F();
}
var newObject = object(oldObject);

I can see some appeal in Crockford's technique above. I do
see some inefficiency in the code above as the little
dance with F() and its prototype needs to occur for every
object created.

The assigning to the prototype does need to happen every time, but I
don't see why it is necessary to have a new constructor created for each
execution of the function. It would not seem too much trouble to write
it as:-

var object = (function(){
function F(){}
return (function(o){
F.prototype = o;
return new F();
});
})();

- and re-use a single constructor.
What concerns me more is his suggested use in the above
link of object() function in combination with what he
calls "maker functions" and "parasitic inheritance".

-------

When I first watched Crockford speak about parasitic
inheritance it took something similar to the following
form where person() and employee() are maker functions.

function person(first) {
return {
first: first,
getName: function() {
return this.first;
}
};
}

function employee(first, position) {
var that = person(first);
that.position = position;
that.getPosition = function () {
return this.position;
};
return that;
}

var giselle = employee("Giselle", "hot model");
giselle.getName();

The above code is inefficient as the functions objects
referenced by the getName and getPosition are not shared
by all employee objects. This leads to triple memory use
compared with a standard JavaScript formulation using a
function as a constructor with the getName and getPosition
functions as properties of the constructor's prototype.

That isn't the only way of getting rid of the needless creation of
multiple functions instances:-

var person = (function(){
function forGetName(){
return this.first;
}
return (function(first){
return ({
first:first,
getName:forGetName
});
});
})();

var employee = (function(){
function forGetPosition(){
return this.position;
}
return (function(first, position){
var that = person(first);
that.position = position;
that.getPosition = forGetPosition;
return that;
});
})();

var giselle = employee("Giselle", "hot model");
giselle.getName();

- but I can certainly see why an example like may seem inappropriate in
an example that was talking about styles of inheritance.
-------

Now Crockford is recommending his prototypal system with
the object() function in combination with parasitic
inheritance. I haven't seen clear examples where he is
augmenting functions in the "prototype object chain". It
seems he has used parasitic inheritance more for augmenting
non-function valued properties: building up a hash. I am
not clear how Crockford would implement his recommendation with
multiple levels of makers where functions are augmented but he
does mention "secret" variables and privileged function
properties. This seems to lead in the direction of
inefficiencies of the parasitic example above where the
privilaged function objects cannot be shared.

It is in the nature of 'privileged' functions that they must be unique
(have a one-to-one relationship with the closured used to store the
'private' variables/methods. The inefficiency above comes from the fact
that these examples are not really 'privileged' functions and could be
shared.

It may be that you are seeing code that is intended only to be
illustrative of one possibility in javascript as being intended to be
specifically definitive of the intended application of that possibility.
That seems to be what happened with "Crockford's module pattern", where
individuals observed one illustration of the possibility (a 'singleton'
implementation) and took that as definitive of the module pattern, and
then expended their effort 'creating' (and naming) specific variations,
where such variations had always been inherent in the module pattern as
a whole (and indeed most considerably pre-date 'singleton'
implementations in the history of the module pattern).

When writing code that is intended to illustrate something specific it
is often best to simplify all other aspects of the code (such as those
that may impact on efficiency) in order to not distract attention form
what is important to the subject. It is also normal to provide very
limited numbers of examples (often only one) even when endless
possibilities would exist.
------

A while ago I played with using prototypes a different way
than I normally do to really emphasis the building up of
complete prototype objects. Below is my thinking translated
to use Crockford's object() function. In this way the getName
and getPosition functions are shared in memory.

function object(o) {
function F() {}
F.prototype = o;
return new F();
}

// build up a prototypical person
var adam = {
first: 'Adam',
getName: function() {
return this.first;
}
}

// a person maker function
function person(first) {
var p = object(adam);
p.first = first;
return p;
}

// build up a prototypical employee
var homer = person('homer');
homer.position = 'safety';
homer.getPosition = function() {
return this.position;
}

// an employee maker function
function employee(first, position) {
var e = object(homer);
e.first = first;
e.position = position;
return e;
}

var giselle = employee("Giselle", "hot model");
giselle.getName();

---------

The above example could easily be written in the normal
JavaScript way without the need for the object() function.

var adam = {
first: 'Adam',
getName: function() {
return this.first;
}
}

function Person(first) {
this.first = first;
}
Person.prototype = adam;

var homer = new Person('homer');
homer.position = 'safety';
homer.getPosition = function() {
return this.position;
}

function Employee(first, position) {
this.first = first;
this.position = position;
}
Employee.prototype = homer;

var giselle = new Employee("Giselle", "hot model");
giselle.getName();


It seems to me that this last example is quite similar to the
previous example. This example is, in fact, more declarative
than the previous example because in this last example there
are lines like "Person.prototype = adam;" which says what it
means quite clearly.

Maybe, in the sense that it says something, but I don't see any need to
have an 'adam' object at all. It may as well just be an (anonymous)
object assigned to Person.prototype. Indeed this strikes me as the more
normal javascript prototype inheritance approach to this code:-

function Person(first) {
this.first = first;
}
Person.prototype = {
first:'',
getName:function() {
return this.first;
}
};

function Employee(first, position) {
this.first = first;
this.position = position;
}
Employee.prototype = new Person('');
Employee.prototype.position = 'safety';
Employee.prototype.getPosition = function() {
return this.position;
};
This example is also more efficient (although perhaps just
slightly) without the need for the "F() dance" in object().
This example uses language-level constructs which which
JavaScript programmers are familiar. Even disregarding
the object() function's length, this example is shorter.

Yes (though I would perceive it as Lasse Reichstein Nielsen's "clone"
function, and write it the way I illustrated above (or using the
'Russian Doll' pattern)), but it serves a specific purpose and is not a
universal panacea for inheritance.

There is a great deal to be said for 'inheriting' form specific object
instances. In the system I work with it is necessary to employ multiple
instances of fairly complex object that individually have complex
one-time set-up operations and a re-occurring configuration phase, but
are such that it is possible (indeed likely) that more than one instance
will exist at a time which should have undergone the same one-time
set-up. I speed this process up by having the system recognise when an
object already exists that has undergone the necessary one-time set-up
and then just uses that object as the prototype of a new object, with
the re-occurring configuration acting to mask the instance specific
aspects of the object being inherited from.
Do you see the apparent ugliness that Crockford seems to
see in the JavaScript built-in system of constructor
functions, their prototype objects and the "new" keyword?

The traditional object defining structures are a little "ragged" in my
opinion.
Is there precedence for Crockford's object() function from
another language?

I don't know (as it would have to be a language that uses prototype
inheritance and I don't know how to use any others).
Should the JavaScript language have an facility like
Crockford's? object() function?

The javascript language has a facility like "Crockford's object
function", else you could not see it above.
How would you code this Person-Employee example?

What is the specification?
If you happen to be Douglas Crockford, how badly have
I misinterpreted your writing and speaking?
<snip>

Richard.
 
P

Peter Michaux

Peter Michaux wrote:














Maybe, in the sense that it says something, but I don't see any need to
have an 'adam' object at all.

Neither do I. It was more an exercise to try and focus on complete
prototypes perhaps in a philosophical sense. I don't imagine Plato or
Aristotle idealizing a partial horse prototype with certain details
filled in by all instances based on that prototype. The way that a
constructor function's prototype object is usually used in JavaScript
is a bit of a template pattern. For example, the person prototype
wouldn't necessarily have a name property but would have the ability
to say its name which is a bit odd.

It may as well just be an (anonymous)
object assigned to Person.prototype. Indeed this strikes me as the more
normal javascript prototype inheritance approach to this code:-

I should not have written that the above is "normal JavaScript." I
should have written the second version is closer to the normal
JavaScript way of doing things using the prototype property of the
constructor and "new".

function Person(first) {
this.first = first;}

Person.prototype = {
first:'',
getName:function() {
return this.first;
}

};

function Employee(first, position) {
this.first = first;
this.position = position;}

Employee.prototype = new Person('');
Employee.prototype.position = 'safety';
Employee.prototype.getPosition = function() {
return this.position;

};

I agree that your code above is almost exactly what is usually
considered normal JavaScript.

The things that bother me about examples like these are the
duplication of the initialization of the person (ie
"this.first=first;") in the Employee function. There are several ways
to factor this out of the Person() function and then call this
initialization code from both constructors however no particular
technique I've tried has struck me as elegant.

Also sending the empty string in the "new Person('')" line.
Crockford's technique and several others that use dummy constructors
(ie F()) avoid this which I think is probably good.


Yes (though I would perceive it as Lasse Reichstein Nielsen's "clone"
function,

I'll search the archives sometime for this. The first time in
encountered this sort of function it helped when I realized it was a
"live clone" and changes to the prototype continued to affect the
clones.

<snip>

Thanks for your thoughts, Richard.

Peter
 
B

Brian Adkins

don't see why it is necessary to have a new constructor created for each
execution of the function. It would not seem too much trouble to write
it as:-

var object = (function(){
function F(){}
return (function(o){
F.prototype = o;
return new F();
});

})();

- and re-use a single constructor.

FYI - I ran a simple benchmark (below), and the execution time (best
of 5 runs) using Crockford's version was 37% longer than yours. That's
a pretty significant speedup.

var foo = {};
var bar = null;
var t1 = new Date();
for (var i = 0; i < 300000; ++i) {
bar = object(foo);
}
var t2 = new Date();
alert ('elapsed time = ' + (t2.getTime() - t1.getTime()) + ' ms');
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top