Voice of a Developer: JavaScript Objects


JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript. What mistakes a developer generally makes and what differences they should be aware of. 
In part 1, we learned about Data Types and touched on Objects. But part 2 will focus in detail on Objects. You can go through Part 1 from here,
Voice of a Developer: JavaScript Data Types.

Q: Can you use save as a reference in Javascript like we have in other programming languages?

Yes, let’s go back in C / C++ days where we have a concept of pointers,
int x=49;
int *ptr;
ptr = &x;
This means that address of x is stored in ptr.
Therefore, ptr is pointing to an integer. The advantage of this is you could change the value in x via a pointer
printf(“%d”, x); // 50
Similarly, in Javascript the primitive data is saved-as-value. On the contrary, the save-as-reference mechanism is there for objects,
> var person = {name: "Sumit"};
> var anotherPerson = person;
> person.name = "Ravi";
> console.log(anotherPerson.name); // Ravi
> console.log(person.name); // Ravi 
The variable is a reference, not a value

Object Own and Inherited Properties

The own properties are properties that were defined on the object, while the inherited properties were inherited from the object’s Prototype object.
We learned about own properties in part 1, ex- person.name // own property
Prototypal inheritance – Inherited property
In most OOPS based languages, classes inherit from classes. In Javascript, it’s prototype-based. Objects inherit from Objects. And, we know an object is a prototype of classes. Therefore, it’s the prototypical based inheritance

Q: How do we implement prototypal inheritance?

Ans: Use the property called __proto__
> var automobile = {engine: true};
> var car = {tyres: 4}; 
Now, we know the car is a type of automobile, so we could inherit from the automobile.
> car.__proto__ = automobile; //inheritance
> car.engine; // true
Hence, there is CAR => Automobile (car is an automobile)
Own properties are enumerable. This means you can iterate over these
Inherited properties are non-enumerable. These are hidden unless asked specifically
Ex- car.tyres
Ex car.engine
Object.keys (car) //tyres;
car.propertyIsEnumerable("tyres"); //true
car.hasOwnProperty("engine"); //false
car.hasOwnProperty("tyres"); // true
car.propertyIsEnumerable("engine"); //false

Q: Is __proto__ the only way to prototypal inheritance?

Ans: No, you could you Object to create it,
var automobile = {engine: true};
var car = Object.create(automobile); 
Now, you could see car.engine is available

Q: Is there any other way to check the property in an object?

Ans: Yes, you could use the below pattern to validate,
> "engine" in car; //true
> "valueOf" in {}; //true
Read more articles on JavaScript