Home > Web Front-end > JS Tutorial > body text

JS类中定义原型方法的两种实现的区别_javascript技巧

WBOY
Release: 2016-05-16 19:17:39
Original
1058 people have browsed it

我们知道,给JavaScript类添加原形(prototype)方法是很简单的。而且常用的有下面这两种方法,可是这两种方法在使用时有区别吗?

    JScript Class:
 function JSClass()
 {

 }
    Extends prototype method:
 JSClass.prototype.MethodA = function()
 {

 };
    Or

 function = JSClass.prototype.MethodA()
 {

 };
其实这两个原形定义方式可以简化一下来讨论,先把它们看作是两个函数,如下: 
  Foo1(); 

  function Foo1() 
  { 
      alert(’This is Foo1.’); 
  }
     和   Foo2(); 
  var Foo2 = function() 
  { 
      alert(’This is Foo2.’); 
  }

     运行第一个显然是不会有任何错误的,可是运行第二个就有问题了,这时系统会说:Microsoft JScript runtime error: Object expected。这就是说函数定义(Foo1)在脚本解析器中有最高的初始化优先级,这个很好理解。如果不优先处理函数,那么对于函数中的函数调用就没有办法处理了,假使我们先定fn1()再定义fn2(),却从fn1中调fn2,那么就通不过解析了。为什么Foo2不能被初始化,Foo2的定义根本不是函数定义,它是一个标准的赋值语句,之所以能象标准函数一样的使用Foo2(Foo2()),完全是因为它指向的是一个函数对象的实例而已。
再来看原形方法导入里的两种方式,就很简单了。并且不同的执行优先循序,也决了它们在使用中的不同,看如下示例: 
<script> <br>function NormalClass() <br>{ <br> this.m_Property1 = &#146;P1 in Normal Class.&#146;; <br> this.m_Property2 = &#146;P2 in Normal Class.&#146;; <br><br> this.toString = function() <br> { <br> return &#146;[class NormalClass]&#146;; <br> } <br><br> return new InnerClass(); <br><br> function InnerClass() <br> { <br> this.m_Property1 = &#146;P1 in Inner Class.&#146;; <br> this.m_Property2 = &#146;P2 in Inner Class.&#146;; <br><br> this.toString = function() <br> { <br> return &#146;[class InnerClass]&#146;; <br> } <br> } <br><br> InnerClass.prototype.Method1 = function() <br> { <br> alert(this.m_Property1); <br> }; <br><br> function InnerClass.prototype.Method2() <br> { <br> alert(this.m_Property2); <br> }; <br>} <br></script>

     执行: 
var nc = new NormalClass(); 
nc.Method1(); 
nc.Method2();

     是什么效果?为什么? 

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!