3 Answers 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
gion_13
41.5k10 gold badges99 silver badges111 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
marekful
15.4k6 gold badges39 silver badges63 bronze badges
4 Comments
phant0m
This will break as soon as
o.f is passed as a parameter(stored as variable etc...)marekful
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.
phant0m
I'm not critisizing, just pointing out what to be aware of ;)
marekful
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.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
tmaximini
8,4937 gold badges50 silver badges69 bronze badges
lang-js
cis$.