I have a javascript class that I’m creating. This class has private and public functions/properties. My understanding of private and public was that this was public and var was private to that function and its members. However, within the local function buildFramework(), when I call the var settings.currentView I get the error:
settings.currentViewis not defined
My question is, what is the difference between this and var in the scope of a function and its members as well as the global scope?
namespace('example');
example.InstagramViewer = function (options) {
// this works when called within buildFramework()
this.settings = $.extend({
currentView: 'grid'
}, options);
// this doesn't work when called within buildFramework()
var settings = $.extend({
currentView: 'grid'
}, options);
var viewer;
this.init = function () {
buildFramework();
};
var buildFramework = function() {
viewer = $(viewerWrapper).append('<div id="instagramViewer" class="' + settings.currentView + '"></div>'); // this doesn't work
viewer = $(viewerWrapper).append('<div id="instagramViewer" class="' + this.settings.currentView + '"></div>'); // this does work
};
}
and called like so…
$(function () {
var viewer = new connectionsAcademy.publicWebsite.web.js.teenWebsite.InstagramViewer();
viewer.init();
});
There are a lot of differences here.
First, ‘this’ is a keyword which is a reference to the calling object. If you call your function as is, the window will be the calling object and you are setting a global variable by using the the keyword ‘this’.
However, if you call your function through another object, window will no longer be the calling object and instead of setting a global variable you will be setting a member variable on that object.
using ‘var’ in both these cases makes no difference. ‘var’ works different then ‘this’ because it affects no object besides what we will call the function’s scratchpad. Only the function can access its scratchpad (unless you create some kind of closure which exposes a variable on this scratch pad). This is why you can think of a variable defined with ‘var’ as being private.
using ‘var’ is also different then ‘this’ when dealing with ‘delete’. ‘delete’ will not work on a variable declared with ‘var’, but it will when defining a variable on ‘this’ or any other object.
My explanation is crude, but this is a big subject that can not be easily explained in this context. I highly recommend you read this book http://shop.oreilly.com/product/9780596000486.do. Especially chapter 7.