/    Sign up×
Community /Pin to ProfileBookmark

Am i a function or a constructor?

I was wondering if there is a way to determine from within a function body whether it is currently being used as a function, or used to construct a new object.

function Foo() {
/* Can I figure out here if I am currently constructing a new object, or just returning a value? */
}

var foo1 = new Foo();
var foo2 = Foo();

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@KorJul 22.2009 — Check the function's [B]constructor[/B] property
<i>
</i>function Foo(){
if(this.constructor==Foo){alert('called with new')} [COLOR="SlateGray"]// creates an object[/COLOR]
else{alert('called as function')} [COLOR="SlateGray"]// does not create an object[/COLOR]
}

More about the [B]constructor [/B]property:

http://www.w3schools.com/jsref/jsref_constructor_array.asp
Copy linkTweet thisAlerts:
@fetmataauthorJul 22.2009 — Thank you Kor. You are now my mentor ?
Copy linkTweet thisAlerts:
@KorJul 22.2009 — Speaking about the [B]constructor[/B]... Interesting is that property is not readonly (at least not in all the cases). Strange enough, any kind of object, except for primitive such as Number, String and Boolean, can be modified:
<i>
</i>function Foo(){}
var myObj= new Foo(); // new created Object
var myString= new String('blah');// new created String
var myPrimiveString='blah'; // primitve String

myObj.constructor=Array;
myString.constructor=Array;
myPrimitiveString.constructor=Array;

alert([
myObj.constructor===Array,
myString.constructor===Array,
myPrimitiveString.constructor===Array
])

// alerts true,true,false


That's rather bad news for those who use serializer libraries or JSON parsers... Anyway, this is probably another topic ?
×

Success!

Help @fetmata spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...