Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example from: "Javascript - The Good Parts"

What "ugliness" does the following solve? There's something I'm not getting, and I'd appreciate help understanding what it is.


For example, by augmenting Function.prototype, we can make a method available to all functions:

Function.prototype.method = function (name, func) {
     this.prototype[name] = func;
     return this; 
};

By augmenting Function.prototype with a method method, we no longer have to type the name of the prototype property. That bit of ugliness can now be hidden.

like image 690
Matrym Avatar asked Jun 01 '10 06:06

Matrym


1 Answers

Well, ugliness is subjective, but let's see.

You usually write:

function Foo () {}
Foo.prototype.method1 = function ()  { /*...*/ };
Foo.prototype.method2 = function ()  { /*...*/ };

You extend the prototype object a constructor function with the properties that you want to be inherited to the instances created by the new operator.

For example with var obj = new Foo(); you are creating an instance of the Foo constructor, that object will inherit the all the properties bound to the Foo.prototype object and other objects higher in the prototype chain.

The Crockford's method does the same, that method is defined in the Function.prototype object, all functions inherit from that object, so you can call the method like this:

function Foo () {}
Foo.method('method1', function () { /*...*/ });
Foo.method('method2', function () { /*...*/ });

It basically just hides the prototype word from the code, which Crockford considers ugly...

"JavaScript The Good Parts" is a really good book, but I think is based on the personal perspective that Douglas Crockford has of the language.

I agree with him with a lot of things, but I also disagree with some aspects...

like image 71
Christian C. Salvadó Avatar answered Oct 21 '22 05:10

Christian C. Salvadó