473,563 Members | 2,895 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Crockford's JavaScript OOP system

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(oldObjec t);

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.getPositio n = function () {
return this.position;
};
return that;
}

var giselle = employee("Gisel le", "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.getPositi on = 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("Gisel le", "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.prototyp e = adam;

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

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

var giselle = new Employee("Gisel le", "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.prototy pe = 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.croc kford.com/prototypal.html >

Crockford's page mentioning parasitic inheritance
<URL: http://javascript.croc kford.com/inheritance.htm l>

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.croc kford.com/tdop/tdop.html>

Oct 21 '07 #1
2 2497
On Oct 21, 2:12 pm, "Richard Cornford" <Rich...@litote s.demon.co.uk>
wrote:
Peter Michaux wrote:
<snip>
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.getPositi on = 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("Gisel le", "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.prototyp e = adam;
var homer = new Person('homer') ;
homer.position = 'safety';
homer.getPositi on = function() {
return this.position;
}
function Employee(first, position) {
this.first = first;
this.position = position;
}
Employee.protot ype = homer;
var giselle = new Employee("Gisel le", "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.prototy pe = 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.
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.prototyp e. 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.prototyp e = {
first:'',
getName:functio n() {
return this.first;
}

};

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

Employee.protot ype = new Person('');
Employee.protot ype.position = 'safety';
Employee.protot ype.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=fir st;") 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.
<snip>
Do you see advantages to using Crockford's object() function?

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

Oct 22 '07 #2
On Oct 21, 5:12 pm, "Richard Cornford" <Rich...@litote s.demon.co.uk
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.
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');

Oct 29 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

76
4000
by: lorlarz | last post by:
Crockford's JavaScript, The Good Parts (a book review). This shall perhaps be the world's shortest book review (for one of the world's shortests books). I like Douglas Crockford (because I am a crabby old man too; plus he _is_ smart and good).. But, how can he write a book on the good parts of JavaScript and not mention functions that...
8
2659
by: Martin Rinehart | last post by:
The Dojo Style Guide suggests prepending an underscore to indicate a "private" variable. Crockford says don't; JavaScript doesn't have privates. Which should be the convention? I'll vote first: Dojo. Crockford is correct, but I find his logic broken. The prepended underscore says clearly "If we had 'private's this would be one of them."...
0
7583
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7888
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7642
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5484
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3643
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2082
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1200
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.