Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it acceptable to add an attribute to a JavaScript function?

Is it acceptable to add an attribute or value to a JavaScript function?

Example:

var f = 1;

function foo (param) {
    f++;
}

var fooFunc = foo;

fooFunc.dummy = f;

console.log('fooFunc: ' + fooFunc);
console.log('fooFunc.dummy: ' + fooFunc.dummy);

The above example creates a function (foo), then assigns it to a new variable (fooFunc) and then adds a dummy attribute to fooFunc.

When run, this example prints the text of the function first, and then it prints the expected value (1 in this case). When printing the function, it doesn't show any indication of the dummy value:

fooFunc: function foo(param) {
    f++;
}
fooFunc.dummy: 1 

JsFiddle here - open the browser's JavaScript console to see the log messages: http://jsfiddle.net/nwinkler/BwvLf/

Why does this work? And where is the dummy attribute stored, and why isn't it printed when I log the function?

Lastly, even if this works, is it a good idea (or an acceptable practice) to use this? I don't want to start an open ended discussion on this, but rather see if there's documented uses of this, or people discouraging this in JavaScript coding guidelines.

like image 489
nwinkler Avatar asked Nov 23 '25 05:11

nwinkler


2 Answers

Everything except primitives ( null, undefined, number, string, boolean ) in JavaScript are objects. So functions are basically objects.

Objects in JavaScript can have properties and methods, hence functions too.

all functions inherit from Function.prototype and has certain properties ( name, length ) and methods ( .call, .apply ) coming through this chain.

It is sometimes very useful to keep properties attached to the function itself, like cache information, number of invocations etc. There is nothing wrong out in using it this way.

More details : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

like image 181
sreekarun Avatar answered Nov 25 '25 19:11

sreekarun


Let's have a look at ECMAScript documentation (Which is the standard JavaScript is based on). Here's the 3rd. version of it:

http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf

Go to chapter 15, Native ECMAScript Objects. 15.3 > Function objects.

There's a lot of interesting information there concerning your question, but the first thing worth noticing is that function is an object. As an object, it has attributes (predefined and that you can assign yourself). For example, try:

console.log('fooFunc.name: ' + fooFunc.name);

It should display "foo" in your case. Since it's documented quite well, you can use it as a standard way, though it is not so well-spread and may seem a bit unusual.

Hope this helps.

like image 23
Sam Braslavskiy Avatar answered Nov 25 '25 19:11

Sam Braslavskiy