Search code examples
javascriptcalling-conventionfunction-object

Is function object created by `new` constructor treated as mutable object in javascript?


From study, I understood that in javascript, mutable objects() are treated by call-by-reference, and immutable objects are treated by call-by-value calling convention.

Let's say I use this kind of data,

var Node = function(data) {
  this.data = data;
  this.next = null;
};

var v = new Node(0);

is v a mutable object or an immutable object??


Solution

  • First of all lets understand what is the new operator doing inside the created execution context behind the scenes:

    It will:

    1. Create a new Object (and attach it to the this label)
    2. That new object's __proto__ property will reference the function's prototype property
    3. It will return the newly created object (if you are not explicitly returning an object)

    So in your case:

    var v = new Node(0);
    

    v is actually an Object (the one that created and returned via new) and objects in JavaScript are mutable.

    Here are the primitives (immutable) types:
    Boolean
    Null
    Undefined
    Number
    String
    Symbol (new in ECMAScript 6)