I'm learning to define 'class like' function on JavaScript using the prototype property.
When I'm defining a People
class like so, everything is working great:
var People = function(firstName, lastName){
// public
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function(){
console.log(full_name);
return this;
};
// private
var self = this;
var full_name = function(){
return self.firstName + ' ' + self.lastName;
}();
};
var person = new People('John', 'Smith');
person.fullName(); // => "John Smith"
However, when I'm moving the fullName
method outside of the initial definition like so:
var People = function(firstName, lastName){
// public
this.firstName = firstName;
this.lastName = lastName;
// private
var self = this;
var full_name = function(){
return self.firstName + ' ' + self.lastName;
}();
};
People.prototype.fullName = function(){
console.log(full_name);
return this;
};
var person = new People('John', 'Smith');
person.fullName(); // => "ReferenceError: full_name is not defined"
I'm getting an error. I can't understand why...??