Example from: "Javascript - the good parts"

What ugliness does the following? I don’t get something there, and I would appreciate understanding what it is.


For example, adding Function.prototype, we can make the method available to all functions:

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

When incrementing Function.prototype with a method method, we no longer need to enter a prototype property name. Now this ugliness can be hidden.

+7
javascript function prototype
source share
1 answer

Well, ugliness is subjective, but we'll see.

Usually you write:

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

You extend the prototype object of the constructor with the properties you want to inherit to the instances created by the new statement.

For example, using var obj = new Foo(); you create an instance of the Foo constructor, this object inherits all the properties bound to the Foo.prototype object and other objects located above in .

The Crockford method does the same, this method is defined in the Function.prototype object, all functions are inherited from this object, so you can call the method as follows:

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

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

JavaScript Good Details is a really good book, but I think it's based on the personal perspective Douglas Crockford has.

I agree with him in many ways, but I also disagree with some aspects ...

+15
source share

All Articles