Briz
Briz

Reputation: 536

What is the "this" in an example JS function?

Below is the entire contents of a JS/JQuery file. I didn't write it, but I'm trying to add on to it. I am having trouble understanding what this is referring to. I haven't seen functions set up in this style before (SmartPhone = function() {})

SmartPhone = function()
{
    this.miniMap = new GameModeMap();

    this.init = function()
    {
        var self=this;
        var $PhoneContainer = $("#PhoneContainer");
        $PhoneContainer.append("<div id='PhoneScreen'></div>");
        $PhoneContainer.append("<div class='PhoneButton'></div>");
        $('.PhoneButton').click(function(){self.toggleClicked()});

        this.miniMap.init("#PhoneScreen");

        //append the appMenu
        $("#PhoneScreen").append("<div id='AppMenu'></div>");
        $("#AppMenu").hide();
        initMenu();
        //toggleClicked();
    }

    this.toggleClicked = function() 
    {
        console.log(this);
        $('#PhoneContainer').toggleClass ('clicked');
        $('#PhoneScreen').toggleClass ('vertical');
        this.miniMap.toggle();
        $('#AppMenu').toggle();
    }

    this.init();
}

Upvotes: 0

Views: 134

Answers (4)

Matthew Manela
Matthew Manela

Reputation: 16762

The "this" variable in JavaScript can point to many different things depending on your context. There is a great blog post on this called: Understanding JavaScript’s this keyword

In the context you are showing, this will be bound to the object created from the SmartPhone constructor.

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101614

They're using the Object Functionality of JavaScript.

SmartPhone is essentially a class structure in this example, with init() being the construct (called by the last this.init() line within SmartPhone.

this is refering to the scope, and in this case the object being created.

Upvotes: 2

DJ Quimby
DJ Quimby

Reputation: 3699

this refers to the SmartPhone object. For instance, this.init is defining the init method for the SmartPhone. Later, you could access it by using SmartPhone.init().

Upvotes: 0

Raynos
Raynos

Reputation: 169531

How this works

Live Example

var Construct = function() {
  this.magic = 42;
}
var c = new Construct();
alert(c.magic === 42);

Upvotes: 2

Related Questions