I've been reading Game Design with HTML5 and JavaScript and it introduced me to objects. So after reading the book and working on the projects I decided to take this new found knowledge and integrate objects in my own projects. So here's my question can or should objects call their own functions? For example:
var someObject = {
start: function() {
check();
},
check: function() {
console.log("Check!");
}
};
someObject.start();
The book did show an example with a timer that does this:
var timer = {
start: function() {
var self = this;
window.setInterval(function(){self.tick();}, 1000);
},
tick: function() {
console.log('tick!');
}
};
In the example with timer object it makes a reference to self in order to call the internal function, so does this mean I should use self to call internal functions or is this the proper way to do this with objects? Or best practices? Thanks in advance.
var someObject = {
start: function() {
var self = this;
self.check();
},
check: function() {
console.log("Check!");
}
};
someObject.start();
JavaScript names are lexically scoped, so whenever a name (variable) is encountered in a script, the JavaScript runtime must search up the scopes from where the function was defined.
At the point of definition, this function:
start: function() {
check();
}
doesn't have access to any check
function in its outer scope. Declaring self
and binding it to this
is a technique used to deal with the (somewhat interesting) intricacies of referring to the current object in JavaScript (because the example code uses window.setInterval
).
To reference a function within the current object, it is enough to use this
.
var someObject = {
start: function() {
this.check();
},
check: function() {
console.log("Check!");
}
};