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

As others have said the first version, using "this" results in every instance of the class A having its own independent copy of function method "x". Whereas using "prototype" will mean that each instance of class A will use the same copy of method "x".

Here is some code to show this subtle difference:

// x is a method assigned to the object using "this"
var A = function () {
    this.x = function () { alert('A'); };
};
A.prototype.updateX = function( value ) {
    this.x = function() { alert( value ); }
};

var a1 = new A();
var a2 = new A();
a1.x();  // Displays 'A'
a2.x();  // Also displays 'A'
a1.updateX('Z');
a1.x();  // Displays 'Z'
a2.x();  // Still displays 'A'

// Here x is a method assigned to the object using "prototype"
var B = function () { };
B.prototype.x = function () { alert('B'); };

B.prototype.updateX = function( value ) {
    B.prototype.x = function() { alert( value ); }
}

var b1 = new B();
var b2 = new B();
b1.x();  // Displays 'B'
b2.x();  // Also displays 'B'
b1.updateX('Y');
b1.x();  // Displays 'Y'
b2.x();  // Also displays 'Y' because by using prototype we have changed it for all instances

As others have mentioned, there are various reasons to choose one method or the other. My sample is just meant to clearly demonstrate the difference.

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?