JavaScript定義類和對象的方法,javascript定義對象

來源:互聯網
上載者:User

JavaScript定義類和對象的方法,javascript定義對象

本文執行個體講述了JavaScript定義類和對象的方法。分享給大家供大家參考。具體方法如下:

在JS中,類和對象有多種不同的寫法,因為本人對JS也不怎麼熟,所以就本人的理解來寫,如果哪位朋友發現有不對,請告之,共同學習.
JS定義一個類有兩種定法(我只知道這兩種):

1. 定義函數的方式:
定義:
複製代碼 代碼如下:function classA(a)
{
     this.aaa=a;  //添加一個屬性
     this.methodA=function(ppp)  //添加一個方法
     {
         alert(ppp);
      }
}
classA.prototype.color = "red";  //用prototype方法添加對象的屬性,此方法也適用於類的執行個體(對象)
classA.prototype.tellColor = function() //用prototype方法添加對象的方法,此方法也適用於類的執行個體(對象)
{
      return "color of "+this.name+" is "+this.color;
}
使用方法:
複製代碼 代碼如下:var oClassA=new classA('This is a class example!');  //執行個體化類
var temp=oClassA.aaa;  //使用屬性aaa
oClassA.methodA(temp);  //使用方法methodA
 
2. 先執行個體化Object類的方式
定義:
複製代碼 代碼如下:var oClassA=new Object();    //先執行個體化基礎類Object
oClassA.aaa='This is a class example!';   //添加一個屬性
oClassA.methodA=function(ppp)  //添加一個方法
{
    alert(ppp);
}
oclassA.prototype.color = "red";  //用prototype方法添加對象的屬性
oclassA.prototype.tellColor = function() //用prototype方法添加對象的方法
{
      return "color of "+this.name+" is "+this.color;
}
 
使用方法:
可以直接拿oClassA來用,如:
複製代碼 代碼如下:var temp=oClassA.aaa;  //使用屬性aaa
oClassA.methodA(temp);  //使用方法methodA

希望本文所述對大家的javascript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.