Friday, November 21, 2008

There's something about prototypal inheritance...

Let's look at some JavaScript, and today I'll ask Crockford to pass the sugar:
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
Now let's create an object a, and a two objects b and c based on a.
var a = { name: "a" };
var b = Object.create(a);
var c = Object.create(a); = "c";

At this point both a and b have name "a", and c has a customized name "c". Now lets change a: = "foo";
Objects a and b now have name "foo", and c still gets to keep name "c" (a good language design decision methinks). Since a is just a mutable object we wield this sort of godly power to change or inject DNA. Every time I come back to it, it tickles me.


SteveLee said...

heh, I do like prototype inheritance - it's so dynamic and flexible.

However with this power comes responsibility as you could conceivably end up in a position almost as bad as global variables - you can't easily determine the full impact of a change.

Class hierarchies add a new dimension for writing obscure code with weird dependencies and so do prototypes.

Anyway I'll stop being a merchant of doom. JS rock, almost as much as Python.
Real programmers do it dynamically ;-)

David Bolter said...

@SteveLee, you are so right. The "beware" statement is missing from my post. I'm just having fun playing with raw JS in the console again.

Yeah, I like Python too; hard to like one and not the other.

This blog post wanted to be a lot longer. There's such a fabric of related concepts, patterns, practices that wanted in... :)

Fastbet said...

I think more updates and will be returning. I have filtered for qualified edifying substance of this calibre all through the past various hours. Agen Sbobet