[javascript] Use of 'prototype' vs. 'this' in JavaScript?

What's the difference? => A lot.

I think, the this version is used to enable encapsulation, i.e. data hiding. It helps to manipulate private variables.

Let us look at the following example:

var AdultPerson = function() {

  var age;

  this.setAge = function(val) {
    // some housekeeping
    age = val >= 18 && val;
  };

  this.getAge = function() {
    return age;
  };

  this.isValid = function() {
    return !!age;
  };
};

Now, the prototype structure can be applied as following:

Different adults have different ages, but all of the adults get the same rights.
So, we add it using prototype, rather than this.

AdultPerson.prototype.getRights = function() {
  // Should be valid
  return this.isValid() && ['Booze', 'Drive'];
};

Lets look at the implementation now.

var p1 = new AdultPerson;
p1.setAge(12); // ( age = false )
console.log(p1.getRights()); // false ( Kid alert! )
p1.setAge(19); // ( age = 19 )
console.log(p1.getRights()); // ['Booze', 'Drive'] ( Welcome AdultPerson )

var p2 = new AdultPerson;
p2.setAge(45);    
console.log(p2.getRights()); // The same getRights() method, *** not a new copy of it ***

Hope this helps.

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to prototype

What are the nuances of scope prototypal / prototypical inheritance in AngularJS? Extending an Object in Javascript __proto__ VS. prototype in JavaScript Parse JSON String into a Particular Object Prototype in JavaScript Understanding the difference between Object.create() and new SomeFunction() 'this' is undefined in JavaScript class methods JavaScript: What are .extend and .prototype used for? Calling method using JavaScript prototype Use of 'prototype' vs. 'this' in JavaScript?

Examples related to this

this in equals method React: "this" is undefined inside a component function How to access the correct `this` inside a callback? jQuery $(this) keyword Difference between $(this) and event.target? 'this' vs $scope in AngularJS controllers Difference between getContext() , getApplicationContext() , getBaseContext() and "this" Use of "this" keyword in C++ What is context in _.each(list, iterator, [context])? What does 'var that = this;' mean in JavaScript?