What’s the difference between the syntax in the following two examples?
a.
var Person = function(firstAndLast) {
var fullName = firstAndLast;
this.getFirstName = function() {
return fullName.split(" ")[0];
};
}
var bob = new Person("Bob Ross");
bob.getFirstName();
and b.
function Circle(radius) {
this.radius = radius;
this.draw = function(){
console.log('draw');
}
}
const circle = new Circle(1);
The difference between the two styles of declaring the object is within the closure.
“this” keyword reference to itself is not used for creating private variable, it is meant to be a self reference.
When you create the new Circle object, this keyword is pointing to both radius and object.
When Person is created, fullName is an actual block scope variable which is contained within the scope of a Person. fullName is not destroy because the reference it has to bob that contain the closure.
console.log( bob ); //Person { getFirstName: f }
console.log( circle ); //Circle { radius: 1, draw: f }