zoukankan      html  css  js  c++  java
  • js函数使用prototype和不适用prototype的区别

    js中类定义函数时用prototype与不用的区别

    原创 2017年06月05日 12:25:41
     

    首先来看一个实例:

    function ListCommon2(first,second,third) 
    { 
        this.First=function () 
        { 
            alert("first do"+first); 
        } 
    } 
    //不加prototype的情况
    ListCommon2.do1=function(first) 
    { 
        // this.First(); 
        alert("first do"+first); 
    } 
    //添加prototype的情况
    ListCommon2.prototype.do2=function(first) 
    { 
        // this.First(); 
        alert("first do"+first); 
    } 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    上面添加与不添加prototype有什么区别呢?下面我们来测试这个实例。代码如下:

    var t1=new ListCommon2("烧水1","泡茶1","喝1"); 
    // t1.do1();//调用出错 
    ListCommon2.do1("烧水1"); 
    var t2=new ListCommon2("烧水2","泡茶2","喝2"); 
    t2.do2("烧水2");// 
    // ListCommon2.do2("烧水1");//调用出错 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    经过测试发现,没有使用prototype的方法相当于类的静态方法,因此可以这样调用,ListCommon2.do1(“烧水1”);但如果这样调用就会出错,t1.do1();

    相反,使用prototype的方法相当于类的实例方法,不许new后才能使用,ListCommon2.do2(“烧水1”);这样就会出错

    结论:

    • 使用 prototype定义的方法相当于类的实例方法,必须new后才能使用
    • 不使用prototype定义的方法相当于类的静态方法,可以直接使用,不需要new
    萌橙 你瞅啥?
  • 相关阅读:
    购物英语词汇
    生活学习英语词汇
    银行英语词汇
    烹饪英语词汇
    旅游英语词汇
    饮食英语词汇
    书英语词汇
    王元编辑口语资料中国传统之节日
    DataSet在WCF中怎么办?
    Python生成Wav格式文件
  • 原文地址:https://www.cnblogs.com/daimaxuejia/p/8031204.html
Copyright © 2011-2022 走看看