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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With