Spherical forums

Sphere Development => Sphere Support => Topic started by: Ma3vis on March 02, 2017, 07:44:08 pm

Title: [JS] Question -- Script Help
Post by: Ma3vis on March 02, 2017, 07:44:08 pm

What is the difference between local variables and "this" when writing objects?
Title: Re: [JS] Question -- Script Help
Post by: Fat Cerberus on March 03, 2017, 01:20:15 am
A local variable is just that, "local" to the function it's declared in.  You can think of it as though each function call getting a new copy, so for example:
Code: (javascript) [Select]

function feedPig()
{
    var pig;
    console.log(pig);
    pig = 812;
    console.log(pig);
}

feedPig();
feedPig();


Output:
Code: [Select]

undefined
812
undefined
812


Whereas this refers (usually--it's a bit thornier in JS compared to, say, C++) to the object of a method.  Anything stored on this gets carried around with the object.  Therefore:

Code: (javascript) [Select]

class PigFeeder
{
    feedPig()
    {
        console.log(this.pig);
        this.pig = 812;
        console.log(this.pig);
    }
}

var obj = new PigFeeder();
obj.feedPig();
obj.feedPig();


Output:
Code: [Select]

undefined
812
812 <-- note the difference from above
812