I'm attempting to learn Javascript inheritance and I've read some resources
- Benefits of using `Object.create` for inheritance
- How to "properly" create a custom object in JavaScript?
on Stack Overflow about inheriting objects in Javascript to get started.
My goal is hiding private members from outside and I tought that the Closure way of inheriting and creating objects, even if it is not very memory friendly, might help me so I came up with this code:
"use strict";
//State is 'saved' by the closure capturing the value
var Contact = function(address)
{
this.setAddressTo = function(newAddress)
{
address = newAddress;
};
this.getAddress = function()
{
return address;
}
};
var Person = function(name, surname, address)
{
//Superclass 'constructor' which will inherit everything public
Contact.call(this, address);
//Subclass members
this.getName = function()
{
return name;
};
this.setName = function(newName)
{
name = newName;
};
this.getSurname = function()
{
return surname;
};
this.setName = function(newSurname)
{
surname = newSurname;
};
//Also with the prototype chaining I can access superclass methods
this.setAddressTo = function(newAddress)
{
console.log('Setting address from base class');
Person.prototype.setAddressTo(newAddress);
}
}
Person.prototype = Object.create(Contact.prototype);
var p1 = new Person('#1.Name', '#1.Surname', '#1.Address');
var p2 = new Person('#2.Name', '#2.Surname', '#2.Address');
console.log('P1 is a person ? ' + (p1 instanceof Person)); //Yes
console.log('P1 is a contact ? ' + (p1 instanceof Contact)); //Yes
console.log('P2 is a person ? ' + (p2 instanceof Person)); //Yes
console.log('P2 is a contact ? ' + (p2 instanceof Contact)); //Yes
console.log(p1.getAddress()); //'#1.Address'
console.log(p2.getAddress()); //'#1.Address'
p1.setAddressTo('#1.Other_Address');
p2.setAddressTo('#2.Other_Address');
console.log(p1.getAddress()); //'#1.Other_Address'
console.log(p2.getAddress()); //'#2.Other_Address'
//Should be undefined because it is not accesible
console.log(p1.address);
console.log(p2.address);
The line:
Person.prototype = Object.create(Contact.prototype);
I use it for making the 'instanceof' operator working correctly (which means that a Person object is an instance of Person and Contact)
Is it correct to do this ?
These lines:
var p1 = new Person('#1.Name', '#1.Surname', '#1.Address');
var p2 = new Person('#2.Name', '#2.Surname', '#2.Address');
Is correct calling the function Person() with 'new' ?
To me it makes sense because I will receive a new Object with its prototype set to Person.prototype which has its prototype set to Contact.prototype (I guess) and this will make the newly created object effectively a Person.
The approach that I've posted is valid to achieve inheritance correctly in Javascript or other better best practices exists to achieve the same thing ?