Skip to main content

News

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

[JS] Question -- Script Help

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

  • Fat Cerberus
  • [*][*][*][*][*]
  • Global Moderator
  • miniSphere 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
miniSphere 5.0b2 (stable: 4.8.8) - Cell compiler - SSj debugger - thread | on GitHub
For the sake of our continued health I very much hope that Fat Cerberus does not become skilled enough at whatever arcane art it would require to cause computers to spawn enormous man-eating pigs ~Rhuan