Var vs this in methods


#1

Dear all,

I am a little confused as to when do we use var vs this when creating a new method. Would somebody be able to explain the difference between
1. var returnBalance = new function(){ };
2. this.askTeller = new function(){ };

Why can't we use var askTeller = new function?

Code snippet is as shown below:

function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;

var returnBalance = function() {
return bankBalance;
};

// create the new function here
this.askTeller = function()
{
return returnBalance;
};
}


#2

Inside a function, var gives local scope to a declared variable. That means it cannot be seen or accessed from outside the function. Since var is written in a constructor function, it becomes a variable only accessible from within an object instance. It is now a private variable.


#3

Hi mtf,

Got it! Thank you for your clear explanation. :smiley: