Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object inheritance

Please help me in understanding this piece of code.

var person = {
    'first-name': 'FirstName',
    'last-name': 'LastName',
    'gender': 'Male'
};

var anotherPerson = new Object(person);
anotherPerson.desig = 'Designation';

console.log('Another person designation: ' + anotherPerson['desig'] + ', person designation: ' + person['desig']);

I expected the output to be Another person designation: Designation, person designation: undefined but to my surprise I found it to be `Another person designation: Designation, person designation: Designation.

According to me anotherPerson is extending person object and properties set to anotherPerson should not be visible to person object. Am I wrong here? Or is that both the object are pointing to the same location?

[EDIT]

Now there are even more surprises.

I added the following code to the above.

person.place = 'XYZ';
console.log(person['place'] + ', ' + anotherPerson['place']); // Expected: XYZ, undefined. Result: XYZ, XYZ.

Based on the above result and answers I thought that both objects are referring to the same location. Now I added few more lines

person = undefined;
console.log(anotherPerson['place']) //Expected: error, Result: XYZ. ??!?!?
console.log(person['place']) // Expected: error, Result: error.

Can someone throw some light on me to understand this? Thanks for your help in advance

like image 479
Anji Avatar asked Nov 04 '22 01:11

Anji


1 Answers

You are not doing extending or any kind of inheritance.

This comes closer:

var Person = function () {
    this["first-name"] = 'FirstName',
    this["last-name"] = 'LastName',
    this["gender"] = 'Male'
};

var person = new Person();
var anotherPerson = new Person();

Now you have two seperate instances of Person. If you also want anotherPerson to be a subclass ..

var Person = function () {
    this["first-name"] = 'FirstName',
    this["last-name"] = 'LastName',
    this["gender"] = 'Male'
};

var AnotherPerson = function () {
    this.desig = "Designation";
}
AnotherPerson.prototype = new Person();   // inherit from Person
AnotherPerson.prototype.constructor = AnotherPerson;  // reset constructor

var person = new Person();
var anotherPerson = new AnotherPerson();

console.log(person.desig); // undefined
console.log(anotherPerson.desig); // Designation
like image 153
Halcyon Avatar answered Nov 09 '22 13:11

Halcyon