1

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?

phant0m
17k6 gold badges52 silver badges84 bronze badges
asked Feb 9, 2013 at 13:01
3
  • No, but I have some thoughts about prototypes of functions. Commented Feb 9, 2013 at 13:10
  • What are your thoughts and what do are you trying to accomplish? Commented Feb 9, 2013 at 13:10
  • Just a simple console.log wrapper with options (silent mode, easy groups). Actually c is $. Commented Feb 9, 2013 at 13:26

3 Answers 3

3

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();
answered Feb 9, 2013 at 13:11
Sign up to request clarification or add additional context in comments.

Comments

2

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
answered Feb 9, 2013 at 13:09

4 Comments

This will break as soon as o.f is passed as a parameter(stored as variable etc...)
Yeah, but it's not. It's accessed from within a function that is a property of an object and the function itself has a property too.
I'm not critisizing, just pointing out what to be aware of ;)
Ok, I agree this isn't a good approach, shouldn't be used in robust code. But it still allows to use a condition in that function depending on the value of o.f.prop1 which is a read/write property even from outside of o. So it is flexible and may be useful.
0

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
 }
}
answered Feb 9, 2013 at 13:05

2 Comments

Uhm, depending on what exactly the OP is trying to do, the answer is either yes, or no.
It's not a solution :) I think the better way will be c.log() + c.logProperties, but it's also not a solution.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.