Sign in to follow this  
Ninjadoodle

'this.' vs 'var' questions

Recommended Posts

Hi guys

 

I just wanted to clarify a couple of things ...

 

I understand that if I create some sprites inside 'init' and want to read their co-ordinates inside 'update', I have to use 'this.' instead of 'var' ...

game.module(    'game.stage01').body(function() {game.createScene('Stage01', {    backgroundColor: 0x000000,    init: function() {        var container = new game.Container().addTo(game.scene.stage);        this.hero = new game.Sprite('hero.png');        this.hero.position.set(240*game.scale, 160*game.scale);        this.hero.anchor.set(0.5, 0.5);        container.addChild(this.hero);    },    update: function() {        console.log(this.hero.x);    }});});

1. What happens with things like containers, should I declare them as 'var' or 'this.'?

 

2. I realize vars keep things local (inside it's function), but is there any performance drop using 'this.' all the time?

 

If anybody could elaborate on this a little or point to some info, I would really appreciate it :)

 

Thank you in advance!

Share this post


Link to post
Share on other sites

Here's my two cents, or maybe one and a half...

 

Upshot is, it's about scope.  "var" makes a variable be associated with the "global" window object, whereas var in a function denotes scope for the function object it is used in - as you are already aware.  "this" is a context variable that lets you specify a particular scope which would otherwise would otherwise be associated with global or function scope (could also be function scope via a closure).   In the next major version of JavaScript, there will also be "let", which will allow block scope.

 

Anytime you see a dot ( . ) there will always be some sort of performance hit, but in most cases, it is of no importance.  Loops are where little slowdowns will accumulate and kill you - if you aren't in a loop of some kind, don't even worry about it.  If you are, probably still don't worry about it.  Performance testing is the place to fine tune this kind of stuff, though your instinct to pick the correct architecture from the beginning is absolutely a wise one.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.