在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中的對象。
JavaScript技術:javascript 面向對象編程 萬物皆對象,轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。