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 ('v开发者_开发百科ertical');
this.miniMap.toggle();
$('#AppMenu').toggle();
}
this.init();
}
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.
How this
works
Live Example
var Construct = function() {
this.magic = 42;
}
var c = new Construct();
alert(c.magic === 42);
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.
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().
精彩评论