/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] Calling the Object’s function

Hey

I’m trying to make a script where I click on an element and then the script would like to do different things…

[CODE]function Obj(id,label){
this.id = id;
this.label = label;
document.write(‘<div id=”‘+this.id+'” value=”‘+this.label+'”></div>’);
[COLOR=”Red”]document.getElementById(this.id).onclick=function(){this.doThis();};[/COLOR]
}
Obj.prototype.doThis = function(){
alert(‘doThis called’);
};
var myObj = new Obj(‘theDiv’,’A button’);[/CODE]

I can see the button in my document but when I tries to click on it, I’m getting an error-message:
[I]“The object doesn’t support the property or the method”[/I]
What am I doing wrong?
Thanks for help!

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@Totte_chauthorDec 07.2007 — Don't you have any ideas or don't you understand what I'm trying to do??
Copy linkTweet thisAlerts:
@toicontienDec 07.2007 — You've run into a problem with variable scope. The "this" keyword inside the Obj class constructor function call points to the instance of the Obj class, while the "this" keyword points to the DOM node in the onclick event. You need a function closure:

function Obj(id,label){
this.id = id;
this.label = label;
document.write('&lt;div id="'+this.id+'" value="'+this.label+'"&gt;&lt;/div&gt;');
document.getElementById(this.id).onclick = [B]this.getOnclickFn(this);[/B]
}
Obj.prototype = {
doThis: function() {
alert('this.id is "'+this.id'"nnthis.label is "'+this.label+'"');
},

[B]getOnclickFn: function(instance) {
return function() {
instance.doThis();
};
}[/B]
};
Copy linkTweet thisAlerts:
@Totte_chauthorDec 08.2007 — Thank you! It works! Thank you!!
×

Success!

Help @Totte_ch 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.16,
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: @nearjob,
tipped: article
amount: 1000 SATS,

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

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