Reputation: 11
I am learning PHASER HTML5 game dev framework based on javascript, during which I came across this piece of code which I am not able to understand
var BunnyDefender = {};
BunnyDefender.Boot = function(game) {};
BunnyDefender.Boot.prototype = {
preload: function()
{
//-----to load objects and units before we begin our game
this.load.image('preloadbar', 'images/loader_bar.png');
this.load.image('titleimage', 'images/TitleImage.png');
},
create: function()
{
this.input.addPointer();
this.stage.backgroundColor = '#171642';
this.state.start('Preloader'); // launches preloader from Boot.js
}
};
Here from what I had learnt about javascript prototyping was that , to add any method to an object or constructor function we used the following syntax/example:
function employee(name,jobtitle,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
}
var fred=new employee("Fred Flintstone","Caveman",1970);
employee.prototype.salary=null;
fred.salary=20000;
Please help !!!
Upvotes: 0
Views: 1800
Reputation: 14620
So from what I understand from the question, you are not clear on static methods / properties in javascript.
Static methods can be called any time without creating a new
instance of the class. Static methods are merely related code that may do something such as configure a class or uphold a design pattern such as creating / returning a singleton instance of the class.
// Constructor
var BunnyDefender = {};
// Prototype declarations
BunnyDefender.prototype = { ... }
// Static method implementing a crude singleton
BunnyDefender.Boot = function() {
// Check if the static property _instance exists
// if it doesn't. Create it one time only, thus our
// BunnyDefender singleton is born.
if ( ! BunnyDefender._instance )
BunnyDefender._instance = new BunnyDefender();
// Return the already created instance of BunnyDefender
return BunnyDefender._instance;
};
As Boot
is a static method of the class BunnyDefender
we can call it without creating a new instance of bunny defender.
var bunnyDefender = BunnyDefender.Boot();
You can read more about static properties / methods in javascript tutorials/documentation such as this article.
Upvotes: 1