/    Sign up×
Community /Pin to ProfileBookmark

JS class + events

Hello all.
Im writing a class for context menues in web pages. I have problem with accessing properties of my class from event function. To understand my question i will paste a test code.

[script]
function myClass() {
this.a = ‘test1’;
this.b = ‘test2’;

this.MDown = function () {
alert(this.a); // I need to access variable a from myClass. But this return error because “this” in this case refers to the HTML element the event is handled by
}

document.addEventListener(‘mousedown’, this.MDown, false);
}

var a = new myClass();
[/script]

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@A1ien51Sep 21.2006 — you need to write a closure

var _ref = this;

this.MDown = function () {

alert(_
ref.a); // I need to access variable a from myClass. But this return error because "this" in this case refers to the HTML element the event is handled by

}

Eric
Copy linkTweet thisAlerts:
@A1ien51Sep 21.2006 — Also I highly recommend you read this free chapter from my book on OO JavaScript: http://java.sun.com/javascript/ajaxinaction/Ajax_in_Action_ApB.html

Eric
×

Success!

Help @thec0der 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.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: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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

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