Javascript: functions without prototype

Built- in functions in javascript (for example, Object.keys ) do not have the "prototype" property.

 Object.keys.prototype === undefined; // returns true Array.prototype.slice.prototype === undefined; // returns true 

However, either function(){...} or new Function() will generate a constructor (instance of the function) along with the prototype (instance of the object). Isn't that too expensive?

Is it possible to create a pure function instead of a constructor in javascript?

+7
javascript function prototype
source share
3 answers

Besides Math.random , the built-in functions in JS are pure in design. You should not output a function with a new statement that will not do you the right job.

JavaScript is a multi-paradigm programming language that reveals the feelings of functional and oop . So you have pure functions without a prototype:

 Math.round // whose typeof is function Math.floor // whose typeof is also function 

Above, Math can be thought of as a namespace instead of an object type. Thus, this is just a container that provides you with a set of functions.

In contrast, if you reference prototype object functions in JavaScript, you will get undefined if you don't reference them through prototype:

 Array.map // undefined Array.reduce // undefined 

This is due to the fact that the Array is not intended for a namespace such as Math, it is an object class in the sense of OOP. Therefore, you need to call the function through your instance, for example

 var list = new Array(3); list.map(function(a){ return 1 }); 

Otherwise, you can access the function through prototype to access a pure function where the this object is not bound. See the following instructions:

 var list = [1,2,3]; typeof(Array.prototype.map); // It pure, unbound Array.prototype.map.call( list, function(a){ return a*2 }); // Usage in a purely-functional way 

The meaning of this is that JavaScript is designed to be written in OOP and Functional ways. You may need to play around with the function prototype, as I have given a few examples above, and this will explain you again :)

+2
source share

Question: "What does it mean to create them?"

For all goals and purposes

 function myFunc ( ) { } myFunc.constructor = undefined; myFunc.prototype = undefined; 

will provide you with what you want from a practical point of view.

In ES6, lambdas should not have links to other functions;

 (() => { }).prototype === undefined; // I believe this should be 100% true 

... your other question ...... too expensive that there are added functions / objects created for each function ...

.... well, browsers work happily. Talking about memory consumption from creating functions is usually immeasurably small these days (although there would be a problem for IoT / wearables). This is premature micro-optimization.

+1
source share

This is a pure function when you call it without new

0
source share

All Articles