Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are JavaScript Primitive-Variables immutable and Object-Variables not?

Tags:

javascript

oop

There is a way to add a member-function or member-property to Number, String, ect...-Variables with the help of the prototype-property:

 Number.prototype.member = function(){ console.log('number-member-function called'); };

or with help of the proto-property of the variables themselves:

 var num = 7;
 num.__proto__.member = function(){ console.log('number-member-function called'); };

Just like to any other kind of JavaScript-types. But what is the difference of the implementation of Primtives and Objects in JavaScript so that the code below does not work for Numbers but for Objects?

 var num = 7;
 num.member = function(){ console.log('number-member-function called'); };
 num.member(); // TypeError: num.member is not a function

 var obj = {};
 obj.member = function(){ console.log('object-member-function called'); };
 obj.member(); // object-member-function called

Does anybody know approximatly how JavaScript Primitves and Objects are implemented under the hood? Because all JavaScript-implementations in all browsers must be done identically or almost for there is an error thrown with the Number-Function called member.

like image 296
Blauharley Avatar asked Feb 23 '14 17:02

Blauharley


1 Answers

When you use the literal notation for the boolean, string and number types, the constructors (Boolean, String, Number) are not used. The primitive types still behaves almost like they had been instantiated with the new operator, but are truly primitive types.

Only when you are trying to use them as objects or you are trying to use a property of a constructor, the JavaScript interpreter creates a wrapper object around them behind the scenes. After this, the wrapper objects gets discarded and you are dealing again with the primitive type. So:

var num = 7; //primitive

// You are trying to use num as an object: a wrapper object gets created and discarded just after the assignment
num.member = function(){ console.log('number-member-function called'); }; 

// This will throw an error, because here num is primitive again (member was defined on the discarded wrapper)
num.member();

More on this topic can be found on the book "JavaScript Enlightenment" by Cody Lindley, based on the ECMA-262, Edition 3 specification.

like image 186
Giovanni Filardo Avatar answered Oct 06 '22 01:10

Giovanni Filardo