javascript - How do I run a function on object creation? -


issue:

I'm making an HTML5 canvas game and I want to make an object for myself Ship which specifies the source of the ship for images / postpaid. It works if I make the ship and then assign a variable to src, but I want to know that if I am building the ship, then I can do it once.

This:

  ship = {// one square for my ship x: $ (window). Width () / 2, y: $ (window) .height () / 2, i: new image ()} ship.i.src = "picture / poship.png";   

When I make my ship (to keep things together), then I wanted to do it once something like this:

  Ship = {// one square for my ship x: $ (window). Width () / 2, y: $ (window) .height () / 2, I: new image (), src: function () {this.i.src = "images / powship.png"}}   

But it does not seem to work. / P>

Question:

How can I run a function on object creation?

function ship.src (); is not running, and this is the reason that .src is not set up.

Your ship may wish for more things to run on class creation, so a constructor is justified.

  var ship = function () {// Set the basic components of your square this.x = $ (window) Width () / 2; This.y = $ (window) Height () / 2; This.i = new image (); // Make any construction requirements in advance I.src = "picture / position"; }; Var Ship = New Ship ();   

Or you can do this:

  var ship = function () {result = {x: $ (window) Light () / 2, Y: $ (window) Light () / 2, i: new image ()} result.i.src = "picture / sticky page"; Return result; };    

Comments