I recently looked at this article about this.
In section 4.2, it uses an example similar to your code and emphasizes the trap of forgetting the βnewβ. 'this' in a function call points to a global object (window or browser), so when you return it, you put your functions in a global object and then return a link to it. If you used the new Unit () and did not return it, you would get an object with your functions on it.
You can use bind, but I think it will be something like Unit.bind (Unit), which will look weird.
You can also use the factory function to return an object, and you donβt have to worry about forgetting a new one
function Unit(){ var move = function(direction){ switch(direction){ case 'up': { console.log('foo'); break; } case 'down': { console.log('foooo'); break; } } console.log('bar'); }; var shoot = function(){console.log('zap')}; var actions = { moveUp : function(){ move('up') }, moveDown : function(){ move('down') }, shoot : shoot }; return { actions:actions }; } var player1=Unit(); player1.actions.shoot(); player1.actions.moveDown(); player1.actions.moveUp();
I removed this from the call to move, part of the problem is actions, this is an object, not a function, therefore, although you can use the binding to functions inside the object, you can, just like me in the code, just close above the functions and then set his.
Also, if you use self = this and do not use the new keyword, you still have a link to the window / browser object and create a global scope.
source share