Let's put Crokford's claim to the test:
"By enhancing Function.prototype with a method method, we can now avoid typing the name of the prototype property. That unsightly bit can now be concealed."
In this context, Crokford is suggesting that you have the ability to modify Function.prototype in order to achieve various functionalities for your own use. This involves adding a function to the function.prototype in order to introduce new methods or properties to any function in JavaScript since functions inherit from Function.prototype. Let's dissect your code.
Function.prototype.method = function (name, func) {
In this line, a new method is being added to Function.prototype. This method takes two arguments: name
represents the name of the new method, and func
represents its functionality. You are likely familiar with what methods and properties are. Functions are considered first-class objects in JavaScript, allowing them to have new properties and methods added during runtime.
this.prototype[name] = func;
Here, this refers to the function calling it. [name]
is the method name, and func
is the method's behavior. It adds a new method to the function being passed using array notation. Finally,
return this;
This statement returns the function being passed with a new method attached to it.
I have provided a practical example below:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
function MyFunction(){
this.name='Robin';
}
MyFunction.method('myMethod',function (){ console.log('I am available')});
var newObj=new MyFunction();
console.log(newObj.myMethod());
In this example, MyFunction
is a constructor. Inherited methods can be added to this constructor's prototype using
MyFunction.prototype.myMethod=function(){ ..}
If you utilize MyFunction
as a constructor, this is how you add a method to it. However, by enhancing Function.prototype as mentioned earlier, you can simply call it like
MyFunction.method('myMethod',function (){console.log('I am available'});
This command will implicitly add a new method called myMethod
to MyFunction()
's prototype.
Therefore, there is no need to repeatedly write MyFunction.prototype
every time you want to add new methods to the MyFunction constructor.
This demonstrates the validity of Crokford's assertion.