JavaScript定義類和對象的方法

字號:


    本文實例講述了JavaScript定義類和對象的方法。分享給大家供大家參考。具體方法如下:
    在JS中,類和對象有多種不同的寫法,因為本人對JS也不怎么熟,所以就本人的理解來寫,如果哪位朋友發(fā)現(xiàn)有不對,請告之,共同學習.
    JS定義一個類有兩種定法(我只知道這兩種):
    1. 定義函數(shù)的方式:
    定義:
    復制代碼 代碼如下: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程序設計有所幫助。