Javascript : functions without prototype

Built-in functions in javascript (eg Object.keys ) don't have a "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 Function) along with a prototype (instance of Object). Isn't it too expensive?

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


Apart from Math.random , built-in functions in JS are pure by design. You shouldn't derive a function with new statement which it won't do the right job for you.

JavaScript is a multi-paradigm programming language which exposes both functional and oop senses. So, you have pure functions without prototype:

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

Above, Math could be perceived as a namespace instead of an Object type. So it is just a container which supplies a set of functions for you.

In contrast, if you refer to functions of prototype objects in JavaScript, you will get an undefined unless you refer to them via prototype:

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

This is because of the matter fact that Array is not designed to be a namespace like Math, it is a class of object in OOP sense. So you need to call the function via its instance like:

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

Otherwise, you may refer to the function via prototype to gain access to the pure function where this object is not bound. See following statement:

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

The meaning behind this is, JavaScript is designed to be writable in both OOP and Functional ways. You may need to play around with function prototype as I have given you some examples above and this will clarify you further :)


The question is "what does 'creating' them mean"?

For all intent and purpose,

function myFunc ( ) { }

myFunc.constructor = undefined;
myFunc.prototype = undefined;

will get you what you want, from a practical standpoint.

In ES6, lambdas should have no ties to other functions;

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

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

....well, there are games running happily on browsers. Talking about the memory consumption from making functions is typically immeasurably small, these days (though IoT / wearables would be a concern).
That's a premature micro-optimization.


当你没有new称呼时,这是一个纯粹的功能

链接地址: http://www.djcxy.com/p/26712.html

上一篇: 将char *传递给期望unsigned char的方法*

下一篇: Javascript:没有原型的功能