本文實(shí)例講述了JavaScript定義類和對(duì)象的方法。分享給大家供大家參考。具體方法如下:
在JS中,類和對(duì)象有多種不同的寫(xiě)法,因?yàn)楸救藢?duì)JS也不怎么熟,所以就本人的理解來(lái)寫(xiě),如果哪位朋友發(fā)現(xiàn)有不對(duì),請(qǐng)告之,共同學(xué)習(xí).
JS定義一個(gè)類有兩種定法(我只知道這兩種):
1. 定義函數(shù)的方式:
定義:
復(fù)制代碼 代碼如下:function classA(a)
{
this.aaa=a; //添加一個(gè)屬性
this.methodA=function(ppp) //添加一個(gè)方法
{
alert(ppp);
}
}
classA.prototype.color = "red"; //用prototype方法添加對(duì)象的屬性,此方法也適用于類的實(shí)例(對(duì)象)
classA.prototype.tellColor = function() //用prototype方法添加對(duì)象的方法,此方法也適用于類的實(shí)例(對(duì)象)
{
return "color of "+this.name+" is "+this.color;
}
使用方法:
復(fù)制代碼 代碼如下:var oClassA=new classA('This is a class example!'); //實(shí)例化類
var temp=oClassA.aaa; //使用屬性aaa
oClassA.methodA(temp); //使用方法methodA
2. 先實(shí)例化Object類的方式
定義:
復(fù)制代碼 代碼如下:var oClassA=new Object(); //先實(shí)例化基礎(chǔ)類Object
oClassA.aaa='This is a class example!'; //添加一個(gè)屬性
oClassA.methodA=function(ppp) //添加一個(gè)方法
{
alert(ppp);
}
oclassA.prototype.color = "red"; //用prototype方法添加對(duì)象的屬性
oclassA.prototype.tellColor = function() //用prototype方法添加對(duì)象的方法
{
return "color of "+this.name+" is "+this.color;
}
使用方法:
可以直接拿oClassA來(lái)用,如:
復(fù)制代碼 代碼如下:var temp=oClassA.aaa; //使用屬性aaa
oClassA.methodA(temp); //使用方法methodA
希望本文所述對(duì)大家的javascript程序設(shè)計(jì)有所幫助。
更多信息請(qǐng)查看IT技術(shù)專欄