PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

javascript可以定义实例方法吗

青灯夜游
青灯夜游 原创
2021-11-22 14:03:18 1603浏览

javascript可以定义实例方法,方法:1、利用javascript对象原型引用prototype来实现实例方法;2、在对象实例上直接定义方法;3、通过this指针来定义实例方法。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

1、利用JavaScript对象原型引用prototype来实现实例方法

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、在实例上直接定义方法(对象)

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、通过this指针来定义实例方法  (变量)

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

那么同时咋实例、原型引用上和"this"上定义相同的实例方法后,实例会优先调用哪一个呢?

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

  *  通过运行结果跟踪测试可以看出直接砸实例上的变量的优先级要高于定义在“this”上的;

  *   而定义在“this”上的又高于prototype定义的变量;

 *    即直接定义在实例上的变量会覆盖定义在“this”上和prototype定义的变量,定义在“this'”上的会覆盖prototypetype定义的变量。

【推荐学习:javascript高级教程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。