Dmitry
Dmitry

Reputation: 7553

functions as objects in JavaScript

There is an object c.
It has a function c.log(message)

Is it possible to add some variables for using them like c.log.debug = true?

Upvotes: 1

Views: 190

Answers (3)

gion_13
gion_13

Reputation: 41533

Javascript is a full object-orientated language. That means that almost everything is an object - even functions :

var f = function(){};
alert(f instanceof Function);
// but this statement is also true
alert(f instanceof Object);

// so you could add/remove propreties on a function as on any other object : 
f.foo = 'bar';

// and you still can call f, because f is still a function
f();

Upvotes: 3

marekful
marekful

Reputation: 15361

With little modification it is possible like this:

var o = {f: function() { console.log('f', this.f.prop1) }};

o.f.prop1 = 2;

o.f(); // f 2
o.f.prop1; // 2

Upvotes: 2

tmaximini
tmaximini

Reputation: 8503

It won't work like this. You could instead add the 'debug' flag as a parameter to your function, e.g.

c.log = function(message, debug) {
  if debug {
    // do debug stuff
  }
  else {
   // do other stuff
  }

}

Upvotes: 0

Related Questions