Skip to main content

News

Topic: [JS] Question -- Script Help (Read 3298 times) previous topic - next topic

0 Members and 1 Guest are viewing this topic.
[JS] Question -- Script Help

What is the difference between local variables and "this" when writing objects?

  • Fat Cerberus
  • [*][*][*][*][*]
  • Global Moderator
  • Sphere Developer
Re: [JS] Question -- Script Help
Reply #1
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
neoSphere 5.9.2 - neoSphere engine - Cell compiler - SSj debugger
forum thread | on GitHub