|
在Javascript中真的是萬物皆對象,new出來的東西是對象,方法是對象,連類也都是對象。下面分別來看一下對象、方法和類的對象特征。
1.拿內(nèi)置的Date來看一下吧
復(fù)制代碼 代碼如下:
var time = new Date();
var timeString = time.getFullYear() + "-" +
time.getMonth() + "-" +
time.getDate() + " " +
time.getHours() + ":" +
time.getMinutes() + ":" +
time.getSeconds();
document.write(timeString);
通過 time來操作其所引用的Date對象,可以方便的調(diào)用Date的對象所包含的一系列g(shù)etXX()方法來獲取年月日時(shí)分秒等信息。
可以再看一下String
復(fù)制代碼 代碼如下:
var username = new String("hello world");
document.write(username.length);
變量username引用了new出來的字符串對象,通過username訪問字符串對象的length屬性。
2.方法也是對象
復(fù)制代碼 代碼如下:
function hello() {
alert("hello");
};
var helloRef = hello;
helloRef();
hello是一個(gè)方法,helloRef是一個(gè)引用了hello方法的變量,helloRef和hello一樣都指向了相同的方法對象。也就意味著helloRef也可以執(zhí)行,helloRef()。同理也可以寫出以下代碼。
復(fù)制代碼 代碼如下:
var helloRef = function() {
alert("hello");
};
helloRef();
function(){alert(“hello”)}是一個(gè)匿名方法,當(dāng)然也是對象,用helloRef變量引用該方法對象后,可以通過helloRef來調(diào)用方法。
3.那么類呢?當(dāng)然類也是對象,在Javascript中,不像C#或Java那樣有class關(guān)鍵字用來創(chuàng)建類,而是直接使用方法的關(guān)鍵字來創(chuàng)建類或者叫模擬類。
復(fù)制代碼 代碼如下:
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();
以上創(chuàng)建了一個(gè)Person類型,Person帶有構(gòu)造參數(shù)username和age,通過創(chuàng)建的Person對象可以調(diào)用Person所包含的方法Introduce。下面對代碼做一些修改。
復(fù)制代碼 代碼如下:
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來創(chuàng)建對象。
以上的幾個(gè)例子可能不是很恰當(dāng),但也可以一窺Javascript中萬物皆對象。
下一節(jié)詳細(xì)的談一談Javascript中的對象。
JavaScript技術(shù):javascript 面向?qū)ο缶幊?萬物皆對象,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時(shí)間聯(lián)系我們修改或刪除,多謝。