JS类定义原型方法的两种实现的区别

来源:互联网 发布:金10数据手机软件 编辑:程序博客网 时间:2024/06/11 03:09

常见的2中原型方法如下:

<script> function JSClass() {     alert('This is JSClass');} function JSClass.prototype.MethodA() {      alert('This is MethodA');};JSClass.prototype.MethodB = function() {       alert('This is MethodB'); };</script>


但是也有区别的,主要是编译器给的编译优先级不同,一个是高优先级别的函数,一个是低优先级别的赋值语句

可以运行下面的2段代码就明白了:

代码一:

<script> Foo1();   function Foo1()   {       alert('This is Foo1.');   }  Foo2();   var Foo2 = function()   {       alert('This is Foo2.');   } // Foo2();</script>


代码二:

function NormalClass() {     this.m_Property1 = 'P1 in Normal Class.';     this.m_Property2 = 'P2 in Normal Class.';           this.toString = function()     {          return '[class NormalClass]';     }        return new InnerClass();           function InnerClass()     {          this.m_Property1 = 'P1 in Inner Class.';           this.m_Property2 = 'P2 in Inner Class.';                     this.toString = function()          {               return '[class InnerClass]';          }         }         InnerClass.prototype.Method1 = function()     {          alert(this.m_Property1);     };          function InnerClass.prototype.Method2()     {          alert(this.m_Property2);     };  // return new InnerClass();   }var nc = new NormalClass(); nc.Method1() //没有定义; nc.Method2();//InnerClass.prototype.Method1 = function()依赖于赋值语句的执行,而 function InnerClass.prototype.Method2() 以最高优先级被脚本引擎初始化

参考: JS类定义原型方法的两种实现的区别 

原创粉丝点击