Lets prove corckford's statement:
"By augmenting Function.prototype with a method method, we no
longerhave to type the name of the prototype property. That bit of
ugliness can now be hidden."
Here crockford wanted to say you can manipulate Function.prototype to achieve many different functionality for your personal usage.It is a functionality added to the function.prototype to add new method/property to any function.Functions in javascript inherits form Function.prototype.lets break down your code.
Function.prototype.method = function (name, func) {
in this line Function.prototype is added a new method.This method receive two arguments.name
satands for a new methods name .And func
stands for its functionality.I think you are familiar with what is methods and properties are.Functions are first class object in javascript.So they can be added new properties and methods during runtime.
this.prototype[name] = func;
Here this refers to the function which calls it.[name]
is method name and func
is the method's functionality It adds a new method to passed function using array notation. Then finally
return this;
with this statement passed function is returned with a new method added to it.
Here i have a practical example for you:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
function Myfunction(){ // a constructor function called Myfunction
this.name='robin'; // it has a name property
}
Myfunction.method('mymethod',function (){ console.log(' i am available')}); //adds a method named 'mymethod to Myfunction constructor
var newObj=new Myfunction(); // creates a new instance of Myfunction class
console.log(newObj.mymethod()); //calls mymethod() of newObj
Here myfunction
is a constructor.We can add inherited methods to this constructor's prototype usind Myfunction.prototype.mymethod=function(){ ..}
If you use myfunction as a constructor this is the way you add method to it.But As you've added a new functionality to Function.prototype,you can simply call it like
Myfunction.method('mymethod',function (){console.log('i am available'}); //it will add a method named mymethod to Myfunction's prototype
This statement will add a new method called mymethod
to Myfunction()'s prototype
implicitly.
so you don't have to write Myfunction.prototype.mymethod=function(){ console.log('i am available');
.Instead you can write Myfunction.method('mymethod',function (){ console.log('i am available'});
So it proves it will relieve you from writing Myfunction.prototype
again and again every time you want to add new methods to Myfunction constructor.
So it proves crockford's statement .