/    Sign up×
Community /Pin to ProfileBookmark

variable scope

[CODE]
var Nargle = function() {

var zadlezo = 6;

this.editZadlezo = function() {
zadlezo = 9;
}

this.alertZadlezo = function() {
alert(zadlezo);
}

}[/CODE]

I don’t understand. Calling editZadlezo and then alertZadlezo results in an alert of 6, not 9. The zadlezo inside editZadlezo seems to be only local and hides the zadlezo I want to edit. I have also tried using this, as below, with the result being the same.

[CODE]
var Nargle = function() {

this.zadlezo = 6;

this.editZadlezo = function() {
this.zadlezo = 9;
}

this.alertZadlezo = function() {
alert(this.zadlezo);
}

}[/CODE]

Please tell me how to access/change an object’s variable from within one of its methods.

Thanks!

Grape

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@Declan1991Jun 02.2008 — [code=php]var Nargle = function() {
this.zadlezo = 6;
this.editZadlezo = function() {
this.zadlezo = 9;
}
this.alertZadlezo = function() {
alert(this.zadlezo);
}
}
var a1 = new Nargle();
a1.editZadlezo();
a1.alertZadlezo();[/code]
works no bother. You must have another issue.

A better way to implement this would be using prototypes:[code=php]var Nargle = function() {
this.zadlezo = 6;
}
Nargle.prototype.editZadlezo = function() {
this.zadlezo = 9;
}
Nargle.prototype.alertZadlezo = function() {
alert(this.zadlezo);
}
var a1 = new Nargle();
a1.editZadlezo();
a1.alertZadlezo();[/code]
especially when it gets more complex.
×

Success!

Help @ProGrape 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.24,
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,
)...