js自訂類與對象

來源:互聯網
上載者:User

標籤:

js中建立自訂類與建立對象:
js建立類與AS3,java都有很大的不同,,,下面來看看他的廬山真面目。。
由於js也是一個物件導向的程式設計語言所以也存在像其他語言那樣的建立自訂的類,和通過類來建立對象。
js的類是有一下三部門組成
1、建構函式
2、屬性
3、方法
自訂一個類:

function MyClass(id,age,name){    this.id = id;    this.age = age;    this.name = name;}

從這個類的定義形式可以看出,js定義類的形式和其他語言有很大的不不同,其他語言定義類需要對類進行正式的定義,而js只是使用了function關鍵字來定義一個建構函式就可以了。接下來你就可以使用new關鍵字來建立一個對象了。。

var myClass = new MyClass(12,23,meimei);

從這個類定義中我們也可以看到js和其他語言中的不同:

this.id = id;

其實id這個變數我們並沒有定義。在其他語言中一定會報錯的。。但是js卻可以自動把id當作屬性,因為js無需事先定義好類的屬性,只需為屬性賦值,js會自定建立這些屬性的。其實對象也同樣使用。當為某個對象事先未定義的屬性賦值時,js將自動建立這些屬性。
這種自由建立屬性的方式看起來很好,卻帶來了很多的弊端,當我們在在拼字已有的屬性時,如果不小心拼錯了,這樣就會給對象新加一個屬性。。
為了防止上面的情況出現我們可以通過像其他語言那樣使用set與get:

function MyClass(id,name)    {            this.id = id;            this.name = name ;    }     MyClass.prototype.getId = function ()     {        return this.id;     }     MyClass.prototype.setId = function (id)     {        this.id = id;     }     MyClass.prototype.getName = function ()     {        return this.name;     }     MyClass.prototype.setName = function (name)     {        this.name = name ;     }     var my = new MyClass(123,"weizi");    document.write(my.getId());    document.write(my.getName());    my.setId(345);    document.write(my.getId());

下面是一個具體的執行個體:

<html xmlns="http://www.w3.org/1999/xhtml" ><head><title>標題頁</title><script language="javascript" type="text/javascript">   function MyClass(id,name)    {            this.id = id;            this.name = name ;    }     MyClass.prototype.getId = function ()     {        return this.id;     }     MyClass.prototype.setId = function (id)     {        this.id = id;     }     MyClass.prototype.getName = function ()     {        return this.name;     }     MyClass.prototype.setName = function (name)     {        this.name = name ;     }     var my = new MyClass(123,"weizi");    document.write(my.getId());    document.write(my.getName());    my.setId(345);    document.write(my.getId());</script></head><body>    <p id = "my"></P></body></html>

js自訂類與對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.