javascriptprototype

Difference between adding function to prototype and object literal in javascript


If I have a constructor Quo

var Quo = function (string) {
     this.status = string;
};

and then made a new object using var myQuo = new Quo("confused");

what would be the difference between:

Quo.get_status = function () { 
    return this.status;
};

and

Quo.prototype.get_status = function () { 
    return this.status;
};

Solution

  • Let's suppose you have created myQuo, as you described

    var myQuo = new Quo("confused");
    

    If you define get_status as a property of Quo, then to get the status of myQuo you would have to call Quo.get_status. However, Quo.get_status will need to know the object context (myQuo) to return the correct value of status. You can redefine the function to accept the object as an argument as in the following:

    Quo.get_status = function (quo) { 
      return quo.status;
    };
    var status = Quo.get_status(myQuo);
    

    Alternatively, you could keep the function Quo.get_status as you wrote it in your question, but you will need to invoke the function in a manner that binds myQuo to "this":

    Quo.get_status = function() {
      return this.status;
    };
    var status = Quo.get_status.call(myQuo);
    

    Either solution is awkward. The preferred solution is to take advantage of Javascript's prototype functionality and define get_status as a prototype function that will be locally accessible to all Quo objects, such as myQuo.

    Quo.prototype.get_status = function () { 
      return this.status;
    };
    var status = myQuo.get_status();