zoukankan      html  css  js  c++  java
  • javascript定义类和实例化类

    在Javascript中,一切都是对象,包括函数。在Javascript中并没有真正的类,不能像C#,PHP等语言中用 class xxx来定义。但Javascript中提供了一种折中的方案:把对象定义描述为对象的配方(先看一下例子会比较容易理解)。

         定义类的方法有很多种,这里有两中较为通用的方法,大家参考一下。

         这两种方法均可以解决构造函数会重复生成函数,为每个对象都创建独立版本的函数的问题。

    解决了重复初始化函数和函数共享的问题。


    1、混合的构造函数/原型方式
    //
    混合的构造函数/原型方式
    //创建对象

    function Card(sID,ourName){
        
    this.ID =
     sID;
        
    this.OurName =
     ourName;
        
    this.Balance = 0
    ;
    }

    Card.prototype.SaveMoney 
    =
     function(money){
        
    this.Balance +=
     money;
    };

    Card.prototype.ShowBalance 
    =
     function(){
        alert(
    this
    .Balance);
    };

    //使用对象

    var cardAA = new Card(1000,'james');
    var cardBB 
    = new Card(1001,'sun'
    );

    cardAA.SaveMoney(
    30
    );
    cardBB.SaveMoney(
    80
    );

    cardAA.ShowBalance();
    cardBB.ShowBalance();


    2
    、动态原型方法
    //
    动态原型方法
    //创建对象

    function Card(sID,ourName){
        
    this.ID =
     sID;
        
    this.OurName =
     ourName;
        
    this.Balance = 0
    ;
        
    if(typeof Card._initialized == "undefined"
    ){
            Card.prototype.SaveMoney 
    =
     function(money){
                
    this.Balance +=
     money;
            };

            Card.prototype.ShowBalance 
    =
     function(){
                alert(
    this
    .Balance);
            };
            Card._initialized 
    = true
    ;
        }
    }

    //使用对象

    var cardAA = new Card(1000,'james');
    var cardBB 
    = new Card(1001,'sun'
    );

    cardAA.SaveMoney(
    30
    );
    cardBB.SaveMoney(
    80
    );

    cardAA.ShowBalance();
    cardBB.ShowBalance();

  • 相关阅读:
    js简单地发送一个请求
    浏览器缓存知识归纳
    文本选择问题: css & js
    闭包和重写函数 返回IE浏览器版本号
    新项目启动 考虑问题
    Angular 单元格合并
    pointer-events 使用场景
    移动开发 新建空白页面
    CSS Tip
    垂直居中方法
  • 原文地址:https://www.cnblogs.com/jordan2009/p/1553528.html
Copyright © 2011-2022 走看看