Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicitly add methods to constructor's prototype in JavaScript

Tags:

javascript

The following is a code snippet from Crockford's JavaScript: The Good Parts:

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

Crockford goes onto explain that

"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."

I'm basically at a loss to understand this point. What did we have to do before that we no longer have to do now?

like image 667
George Avatar asked Jan 26 '15 20:01

George


People also ask

What is difference between __ proto __ and prototype?

prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype. Current standards provide an equivalent Object.

Which JavaScript property allows you to add new properties to object constructors?

The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name. The value is only read-only for primitive values such as 1 , true , and "test" .

What is __ proto __ in JavaScript?

__proto__ is a way to inherit properties from an object in JavaScript. __proto__ a property of Object. prototype is an accessor property that exposes the [[Prototype]] of the object through which it is accessed. POSTly is a web-based API tool that allows for fast testing of your APIs (REST, GraphQL).


1 Answers

He's saying that instead of writing:

MyType.prototype.myMethod = function() {
    ..
};

you can write this:

MyType.method("myMethod", function() {
    ...
});

with the possibility (given the return this) of dot-chaining another call:

MyType.method("method1", function() {
    ...
}).method("method2", function() {
    ...
});

Meh.

like image 84
Alnitak Avatar answered Nov 01 '22 16:11

Alnitak