Home >Web Front-end >JS Tutorial >JavaScript Prototypes vs. `this`: When to Use Which?
Prototype vs. 'this' in JavaScript
In JavaScript, classes are defined through functions that serve as constructors. However, there are differences in how properties and methods are defined within these functions.
Using 'this'
When a method is defined directly within a constructor function, as in the following example:
var A = function () { this.x = function () { // do something }; };
this refers to the newly created instance of the class. In this case, A() creates an instance and sets its x property to the defined function.
Using prototype
In contrast, when a method is defined on the prototype property of the constructor function:
var A = function () { }; A.prototype.x = function () { // do something };
prototype allows multiple instances of the same class to share methods and properties. Assigning a function to the prototype property means that all instances of the class will inherit that method.
Key Differences
When to Use Each Approach
The above is the detailed content of JavaScript Prototypes vs. `this`: When to Use Which?. For more information, please follow other related articles on the PHP Chinese website!