If you define a variable as var, then its scope is limited to the function (it can't be seen from the outside). In OO terms it's somehow like a private property, without actually being a property at all.
If you define a variable as a property (this.name) then it is accessible from the outside.
Same goes for functions. Functions declared inside the scope of the function, but not assigned to a property, are only visible from the inside. If you assign a function to a property you are able to access that function from the outside (as long as the property keeps pointing to that function).
function Person(){
// Declared variable, function scope
var name = "John";
// Property
this.surname = "Doe";
// Assign anonymous function to property
this.getName = function(){
return name;
}
// Assign anonymous function to property
this.getSurname = function(){
return this.surname;
}
// Declare function
function saluteCasually(){
console.log("Hi folks!");
}
// Declare function
function salutePolitely(){
console.log("Nice to meet you");
}
// Assign (not anonymous) function to property
this.salutePolitely = salutePolitely;
}
var person = new Person();
console.log(person.name); // undefined
console.log(person.getName()); // "John"
console.log(person.surname); // "Doe"
console.log(person.getSurname()); // "Doe"
person.saluteCasually(); // Error: person has not a property "saluteCasually".
person.salutePolitely(); // Prints "Nice to meet you";
person.salutePolitely = function(){ // Properties can be messed with from anywhere!
console.log("Bananas");
}
person.salutePolitely(); // Prints "Bananas";