zoukankan      html  css  js  c++  java
  • js中构造函数的执行顺序

    1)在看《web前端修炼之道》中对其中一段代码,一直运行不通

     1 function extend(subClass,superClass){
     2     var F=function(){};
     3     F.prototype=superClass.prototype;
     4     subClass.prototype=new F();
     5     subClass.prototype.constructor=subClass;
     6     subClass.superClass=superClass.prototype;
     7     if(superClass.prototype.constructor==Object.prototype.constructor){
     8         superClass.prototype.constructor=superClass;
     9     }
    10 }
    11 
    12 function Animal(name){
    13     this.name=name;
    14     this.type='animal';
    15 }
    16 
    17 Animal.prototype={
    18     say:function(){
    19         alert("I'm a(an)"+this.type+",my name is "+this.name);
    20     }
    21 }
    22 
    23 extend(Bird,Animal);
    24 
    25 function Bird(name){
    26     this.constructor.superClass.constructor.apply(this,arguments);
    27     this.type='bird';
    28 }
    29 
    30 Bird.prototype.fly=function(){
    31     alert('I am flying');
    32 }
    33 
    34 var canary=new Bird('xiaocui');
    35 canary.say();
    36 canary.fly();

    在第26行始终报错,于是开始注意到构造函数的执行顺序问题。

    2)下面的例子可以看出构造函数,是优先执行的。

     1 C = function(){
     2 alert("1");
     3 this.a();
     4 alert("2");
     5 }
     6  
     7 C.prototype.a=function(){
     8 alert("3");
     9 //alert(name);
    10 alert("4");
    11 }

    运行结果为:在构造函数C内,从上到下执行,先弹出1,后调用方法a,弹出3,执行完a后,最后弹出2,全部执行完后,返回一个队形,并将对象的引用(地址)赋给c.

    3)从《javascript高级程序设计》中可以看到,

      a)自定义的类其实就是定义一个构造函数

         b)同时会通过类的prototype定义类的方法

      c)类的prototype包括两部分:指向构造函数的引用,类的方法

          d)通过构造函数生成的实例,都隐含一个指向类的prototype的引用。

     未完待续。。。

  • 相关阅读:
    OC与JS交互之WKWebView
    iOS下JS与OC互相调用(三)--MessageHandler
    html base64 img 图片显示
    Vue中img的src属性绑定与static文件夹
    XML 树结构
    XML 用途
    XML 简介
    JS Window对象
    JS Math对象
    JS 字符串操作
  • 原文地址:https://www.cnblogs.com/hugh2006/p/3616216.html
Copyright © 2011-2022 走看看