Javascript方法小札记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/livia1234/article/details/44958289

1静态方法

存储在运行内存上的静态区域,该类方法由JS体系内类所持有。

  1. var BaseClass = new Function;  
  2. var Class2 = BaseClass;  
  3. BaseClass.f1 = function(){  
  4. alert("BaseClass ' s static method");  
  5. }  
  6. Class2.f2 = function(){  
  7. alert("Class2 ' s static method");  
  8. }  
  9. BaseClass.f1();//BaseClass ' s static method  
  10. BaseClass.f2();//Class2 ' s static method  
  11. Class2.f1();//BaseClass ' s static method  
  12. Class2.f2();//Class2 ' s static method 

2对象方法

对象方法即创建对象时,以属性的方式创建的方法,同时加入了该对象的原型链中。

3原型方法

一般用于既存的对象,扩展该对象或者扩展继承该对象的对象。将方法动态的添加到对象的原型链中。

  1. var BaseClass = function() {  
  2. this.method1 = function(){  
  3.        alert(' Defined by the "this" in the instance method');  
  4.  }  
  5. };  
  6. var instance1 = new BaseClass();  
  7. instance1.method1 = function(){  
  8.     alert(' Defined directly in the instance method');  
  9. }  
  10. BaseClass.prototype.method1 = function(){  
  11.     alert(' Defined by the prototype instance method ');  
  12. }  
  13. instance1.method1();//Defined directly in the instance method  

通过运行结果跟踪测试可以看出直接定义在实例上的变量的优先级要高于定义在“this”上的,而定义在“this”上的又高于 prototype定义的变量。即直接定义在实例上的变量会覆盖定义在“this”上和prototype定义的变量,定义在“this”上的会覆盖prototype定义的变量。

根据运行测试,可以判断,对象方法创建时,是将方法加入原型链堆栈的最上层,而实例对象中,原型的调用又相对于自身对象方法处于底层。

猜你喜欢

转载自blog.csdn.net/livia1234/article/details/44958289