javascript 物件導向編程 萬物皆對象

來源:互聯網
上載者:User

javascript和java、C#等語言一樣也具有物件導向的一些特徵,但細比較的時候,會發現這些特徵並不是真正的物件導向,很多地方都是利用對象本身來類比物件導向,所以認為javascript不能算是物件導向程式設計語言,而是基於對象的語言。
在javascript中真的是萬物皆對象,new出來的東西是對象,方法是對象,連類也都是對象。下面分別來看一下對象、方法和類的對象特徵。
1.拿內建的Date來看一下吧
複製代碼 代碼如下:var time = new Date();
var timeString = time.getFullYear() + "-" +
time.getMonth() + "-" +
time.getDate() + " " +
time.getHours() + ":" +
time.getMinutes() + ":" +
time.getSeconds();
document.write(timeString);

通過 time來操作其所引用的Date對象,可以方便的調用Date的對象所包含的一系列getXX()方法來擷取年月日時分秒等資訊。
可以再看一下String 複製代碼 代碼如下:var username = new String("hello world");
document.write(username.length);

變數username引用了new出來的字串對象,通過username訪問字串對象的length屬性。
2.方法也是對象 複製代碼 代碼如下:function hello() {
alert("hello");
};
var helloRef = hello;
helloRef();

hello是一個方法,helloRef是一個引用了hello方法的變數,helloRef和hello一樣都指向了相同的方法對象。也就意味著helloRef也可以執行,helloRef()。同理也可以寫出以下代碼。 複製代碼 代碼如下:var helloRef = function() {
alert("hello");
};
helloRef();

function(){alert(“hello”)}是一個匿名方法,當然也是對象,用helloRef變數引用該方法對象後,可以通過helloRef來調用方法。
3.那麼類呢?當然類也是對象,在javascript中,不像C#或java那樣有class關鍵字用來建立類,而是直接使用方法的關鍵字來建立類或者叫類比類。 複製代碼 代碼如下:function Person(username, age) {
this.Name = username;
this.Age = age;
this.Introduce = function() {
alert("我叫" + this.Name + ",今年" + this.Age + "歲了。");
};
};
var person1 = new Person("張三", 20);
person1.Introduce();

以上建立了一個Person類型,Person帶有構造參數username和age,通過建立的Person對象可以調用Person所包含的方法Introduce。下面對代碼做一些修改。 複製代碼 代碼如下:function Person(username, age) {
this.Name = username;
this.Age = age;
this.Introduce = function() {
alert("我叫" + this.Name + ",今年" + this.Age + "歲了。");
};
};
var PersonClass = Person;
var person1 = new PersonClass("張三", 20);
person1.Introduce();

重新聲明新的變數PersonClass並引用Person類,PersonClass和Person都指向了原來的Person所引用的類,所以也可以用PersonClass來建立對象。
以上的幾個例子可能不是很恰當,但也可以一窺javascript中萬物皆對象。
下一節詳細的談一談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.