Alex Rivera | Logout

Javascript objects calling function from itself

Asked 2013-05-30T16:25:34.687
14

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();
Edit
Report

1 Answer

0

of course an object can and should call it's own functions, this is the only way to emulate OOP in javascript. I would say that the practice that the book is using, self = this is bad since this can just be used by itself, however in the first example it is used to preserve the value of this which would otherwise be the this of the function itself not the outer class

answered 2013-05-30T16:28:28.137

Your Answer