Home > Article > Web Front-end > Can JavaScript define instance methods?
Javascript can define instance methods. Methods: 1. Use JavaScript object prototype reference prototype to implement instance methods; 2. Define methods directly on object instances; 3. Define instance methods through this pointer.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1. Use JavaScript object prototype reference prototype to implement instance methods
var BaseClass = function() {}; BaseClass.prototype.method1 = function(){ alert(' This is a instance method '); } var instance1 = new BaseClass(); instance1.method1(); //This is a instance method
2. Directly define methods (objects) on instances
var BaseClass = function() {}; var instance1 = new BaseClass(); instance1.method1 = function(){ alert(' This is a instance method too '); } instance1.method1();//This is a instance method too
3. Define instance methods (variables) through this pointer
var BaseClass = function() { this.method1 = function(){ alert(' Defined by the "this" instance method'); } }; var instance1 = new BaseClass(); instance1.method1();//Defined by the "this" instance method
Then at the same time, define the same instance on the instance, prototype reference and "this" After the method, which one will be called first by the instance?
var BaseClass = function() { this.method1 = function(){ alert(' Defined by the "this" in the instance method'); } }; var instance1 = new BaseClass(); instance1.method1 = function(){ alert(' Defined directly in the instance method'); } BaseClass.prototype.method1 = function(){ alert(' Defined by the prototype instance method '); } instance1.method1();//Defined directly in the instance method
* By running the result tracking test, we can see that the priority of variables directly on the instance is higher than those defined on "this";
* And the variables defined on "this" are higher than the variables defined by prototype;
* That is, the variables defined directly on the instance will overwrite the variables defined on "this" and variables defined by prototype, those defined on "this'" will override variables defined by prototypetype.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of Can JavaScript define instance methods?. For more information, please follow other related articles on the PHP Chinese website!