Voice of a Developer: JavaScript Data Types
Q: Can you use save asa reference in Javascript like we have in other programming languages?
Ans:
Yes, let’s go back in C / C++ days where we have a concept of pointers,
ex:
int x=49;
int *ptr;
ptr = &x;
This means that address of x is stored in ptr.
Therefore, ptr is pointing to integer. The advantage of this is you could change value in x via pointer
Ex:
*ptr=50;
printf(“%d”, x); // 50
Similarly, in Javascript the primitive data is saved-as-value. On the contrary, save-as-reference mechanism is there for objects,
Ex:
> 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 learnt 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 prototypical based inheritance
Q: How do we implement prototypal inheritance?
Ans: Use property called __proto__
Ex:
> var automobile = {engine: true};
> var car = {tyres: 4};
Now, we know car is a type of automobile, so we could inherit from automobile.
> car.__proto__ = automobile; //inheritance
> car.engine; // true
Hence, there is CAR => Automobile (car is a automobile)