/    Sign up×
Community /Pin to ProfileBookmark

Call Member of Class without Object Initiation

Greetings,

Is there any way to call a method of a ‘class’ in without creating an instance of this class?

Thanks

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@mrhooJun 23.2011 — [CODE]There are no classes in javascript.
There are objects with constructor functions.

function Bumbershoot(arg){
for(var p in arg){
this[p]= arg[p];
}
this.report= function(what){
return this[what] || what+' is not here';
}
}
/*
You can't call a method without an instance if it is defined in the constructor

alert(Bumbershoot.report('Mimsey'));

returns >>> ERROR-Bumbershoot.report is not a function

You can call a prototype method without an instance,
but its this is an 'empty' instance of the constructor

Bumbershoot.prototype.report2= function(what){
return this[what] || what+' is not in here';

}
alert(Bumbershoot.prototype.report2('Mimsey'))
returns >>> 'Mimsey is not in here'

And if you have another object that could use the method
you can call it without an instance:

var O={a:1,b:2,c:3,d:4,e:5};
alert(Bumbershoot.prototype.report2.call(O, 'c'))
returns >>> 3
*/[/CODE]
Copy linkTweet thisAlerts:
@rnd_meJun 23.2011 — [CODE]
function Ob(){
this.born = new Date;
}
Ob.prototype.getBirthday=function(){return this.born.toDateString();}

//normal class instantiation:
var o=new Ob;
alert(o.getBirthday());


//without class instance:
alert([0].map(
Ob.prototype.getBirthday,
{born: new Date(2000,0,1)}
));


//borrowing class instance:
alert(
o.getBirthday.call( {born: new Date(1999,11,31)}

));

[/CODE]
×

Success!

Help @objNoob 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 6.2,
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: @meenaratha,
tipped: article
amount: 1000 SATS,

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

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...