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();

原文地址:https://www.cnblogs.com/jordan2009/p/1553528.html