var plugin = {
Init: function() {
this.UpdateUI();
if (this.Status() == 1) {
...
} else {
...
}
},
Status: function() {
...
},
UpdateUI: function() {
...
}
}
This is the basic code. The problem is, when Init is called, the following errors appear:
this.UpdateUI is not a function
this.Status is not a function
Can someone tell me what's the problem with my code?
var plugin = {
Init: function() {
this.UpdateUI();
if (this.Status() == 1) {
...
} else {
...
}
},
Status: function() {
...
},
UpdateUI: function() {
...
}
}
This is the basic code. The problem is, when Init is called, the following errors appear:
this.UpdateUI is not a function
this.Status is not a function
Can someone tell me what's the problem with my code?
Share Improve this question asked Jan 9, 2012 at 19:23 BogdacutuBogdacutu 7717 silver badges24 bronze badges 4-
2
Can you post the code that calls
Init()
? – Frédéric Hamidi Commented Jan 9, 2012 at 19:26 -
scoping issues,
this
isn't referring to plugin, it's referring to the init function. If you placed the Status and UpdateUI functions within the init function, then your code would work correctly. I think bardiir has the correct solution for you. – Cory Danielson Commented Jan 9, 2012 at 19:32 - I think we just found one of the ugly sides of javascript and according to the votes on my answer there seem to be some differenting viewpoints about this :D – bardiir Commented Jan 9, 2012 at 19:40
-
1
@CoryDanielson: We don't know what
this
refers to because we don't know howInit
is being called. But it isn't a scoping issue, and merely placing the functions inside theInit
function will not work. – user1106925 Commented Jan 9, 2012 at 19:42
2 Answers
Reset to default 4That's because this
inside plugin.Init
refers to plugin.Init
and not to plugin
itself. Change it like this:
var plugin = {
Init: function() {
plugin.UpdateUI();
if (plugin.Status() == 1) {
...
} else {
...
}
},
Status: function() {
...
},
UpdateUI: function() {
...
}
}
Prototyped:
function Plugin(){
var self = this;
this.Init = function() {
self.UpdateUI();
if (self.Status() == 1) {
...
} else {
...
}
};
}
Plugin.prototype.status = function() {
...
};
Plugin.prototype.UpdateUI: function() {
...
}
var plugin = new Plugin();
In the Context where init is called this might be something else.
Try to use plugin.UpdateUI
and plugin.Status
instead, that always references the correct functions.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745158179a4614250.html
评论列表(0条)