Jump to content

var vs. this


pete796
 Share

Recommended Posts

Hello,

Can someone explain why you would use a 'var' instead of 'this' ?

In the example below  variables are defined   for 'var r' and 'var scale' 

  buildSpaceRocks: function() {
        this.spacerockgroup = this.add.group();
        for(var i=0; i<this.totalSpacerocks; i++) {
            var r = this.spacerockgroup.create(this.rnd.integerInRange(0, this.world.width), this.rnd.realInRange(-1500, 0), 'spacerock', 'SpaceRock0000');
           
            var scale = this.rnd.realInRange(0.3, 1.0);
            r.scale.x = scale;
            r.scale.y = scale;
           
            this.physics.enable(r, Phaser.Physics.ARCADE);
            r.enableBody = true;
            r.body.velocity.y = this.rnd.integerInRange(200, 400);
            r.animations.add('Fall');
            r.animations.play('Fall', 24, true);
            r.checkWorldBounds = true;
            r.events.onOutOfBounds.add(this.resetRock, this);
        }
    },
    

Many thanks

Link to comment
Share on other sites

Hmm, I think it may be wise to find a javascript tutorial first ;-)

'this' is kind of difficult, but mostly refers to the object that the function is a method of.
'var' is very simple, it is just a container for a value.

Let's say you have a 'var x = 0;' in the global object (the 'parent' of buildSpaceRocks function). To access this variable you use 'this.x' inside buildSpaceRocks.

Link to comment
Share on other sites

ok. great,  this is what I was looking for (no pun)..

Quote
 

'this' is kind of difficult, but mostly refers to the object that the function is a method of.
'var' is very simple, it is just a container for a value.

 

Many thanks

Link to comment
Share on other sites

use let instead of var, and a few other hints on js dev :)

typically in JSGamedev you are quite right by using this for a characters properties etc. all the stats the character needs.
You are doing well by avoiding much global variable declarations as possible. There is a simple reason for that:
if a method uses a variable - it look in it's global scope if it is defined there. If not it looks the above scrope and so on until it finds that variable.

Global Scope polution
For performance you want to keep that lookup as short as possible - (but also considering clean code. If a global var makes absolute sense, use it; but most times it makes no sense).
There is another thing about "this" and variables:

this vs. var usecases
If you need proberties for a character which being kept all the time, you are good to use this, since it's a reference and will not be garbage collected until there is no reference to is (you character is destroyed).

For "short span" calculations - during a method call ... for example: character jumps and there are happening multiple things and calculcations.
You should use var instead of this. Since you don't want to keep an reference to calculated stuff all the time. It is only for the call of that method: use var (or let).
Because when your code is being executed and there is no reference any more- it's being garbage collected.


At least dont use var at all:
why? So, use "let" instead of var. You can google on it, there are a few tutorials on it- But working with let helps you to write better code. Since it has block scope.


regards :)

Link to comment
Share on other sites

Don't worry about `let` and `const` instead of `var`, you're not there yet.

Check out resources regarding scoping in JS, as Milton says, it can get tricky but its critical you get a handle on it and there are many many good resources out there. Use MDN to get started.

Very very briefly, `this` refers to the scope of a function, nothing more. Sounds simple right? Unfortunately (or, fortunately in many cases), JS is dynamic and the scope is very easy to change, which is what makes it tricky. Take the following 'simple' code:

function myLogger (event) {
  console.log(this)
}

// What is the scope here?
myLogger()

// How about when this gets called?
document.body.addEventListener('click', myLogger)

// How about now?
var obj = {
  value: 1,
  log: myLogger
}

obj.log()

Understanding what each one of those calls logs is critical to understanding how scoping works in JS. Make sure you grasp how scope gets mutated in these cases and why that is useful. Note that you need no understanding of object-oriented programming for this, it becomes related but the rules are removed from it. JS is object-oriented (in so much as objects are first-class citizens) but it is prototypal and not classical (ignore the confusing ES2015 class syntax, they aren't real classical classes) so there are some alarming differences if you come from a truly classical OOP language (C, Java etc).

Once you have a handle on the scope of the function from the above code example check out .bind, .apply and .call (again, MDN is your best place to start) and how these built-in functions help you to manage scope. If you're wanting to write in a C/Java-style with pseudo-classes (JS has no proper classes) then you'll need them.

Once you've learnt all this you'll be in a position to completely throw them away if you want, functions are also first-class citizens in JS and it makes a decent stab at being a functional language. It is perfectly viable and attractive to never write `this` into your programs, but only once you've learnt how it works and why it is good/bad will you be in a decision to decide how you want to write stuff.

Link to comment
Share on other sites

1 hour ago, mattstyles said:

Once you have a handle on the scope of the function from the above code example check out .bind, .apply and .call (again, MDN is your best place to start) and how these built-in functions help you to manage scope. If you're wanting to write in a C/Java-style with pseudo-classes (JS has no proper classes) then you'll need them.

Once you've learnt all this you'll be in a position to completely throw them away if you want, functions are also first-class citizens in JS and it makes a decent stab at being a functional language. It is perfectly viable and attractive to never write `this` into your programs, but only once you've learnt how it works and why it is good/bad will you be in a decision to decide how you want to write stuff.

Not a good idea to scare a newbie with these kind of answers :) (or me for that matter).

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...