store={};
store.tang=4;
store.num=3;
document.write(store.tang*store.num);
我們就有了和document.write一樣的用法,這也是對(duì)象的美妙之處,只是這里的對(duì)象只是包含著基本值,因?yàn)?/p>
typeof story.tang="number"
一個(gè)包含對(duì)象的對(duì)象應(yīng)該是這樣子的。
store={};
store.tang=4;
store.num=3;
document.writeln(store.tang*store.num);
var wall=new Object();
wall.store=store;
document.write(typeof wall.store);
而我們用到的document.write和上面用到的document.writeln都是屬于這個(gè)無(wú)序?qū)傩约现械暮瘮?shù)。
下面代碼說(shuō)的就是這個(gè)無(wú)序?qū)傩约兄械暮瘮?shù)。
var IO=new Object();
function print(result){
document.write(result);
};
IO.print=print;
IO.print("a obejct with function");
IO.print(typeof IO.print);
我們定義了一個(gè)叫IO的對(duì)象,聲明對(duì)象可以用
var store={};
又或者是
var store=new Object{};
兩者是等價(jià)的,但是用后者的可讀性會(huì)更好一點(diǎn),我們定義了一個(gè)叫print的函數(shù),他的作用也就是document.write,IO中的print函數(shù)是等價(jià)于print()函數(shù),這也就是對(duì)象和函數(shù)之間的一些區(qū)別,對(duì)象可以包含函數(shù),對(duì)象是無(wú)序?qū)傩缘募?,其屬性可以包含基本值、?duì)象或者函數(shù)。
復(fù)雜一點(diǎn)的對(duì)象應(yīng)該是下面這樣的一種情況。
var Person={name:"phodal",weight:50,height:166};
function dream(){
future;
};
Person.future=dream;
document.write(typeof Person);
document.write(Person.future);
而這些會(huì)在我們未來(lái)的實(shí)際編程過(guò)程中用得更多。
3.3.4 面向?qū)ο?/p>
開(kāi)始之前先讓我們簡(jiǎn)化上面的代碼,
Person.future=function dream(){
future;
}
看上去比上面的簡(jiǎn)單多了,不過(guò)我們還可以簡(jiǎn)化為下面的代碼。。。
var Person=function(){
this.name="phodal";
this.weight=50;
this.height=166;
this.future=function dream(){
return "future";
};
};
var person=new Person();
document.write(person.name+"
");
document.write(typeof person+"
");
document.write(typeof person.future+"
");
document.write(person.future()+"
");
只是在這個(gè)時(shí)候Person是一個(gè)函數(shù),但是我們聲明的person卻變成了一個(gè)對(duì)象一個(gè)Javascript函數(shù)也是一個(gè)對(duì)象,并且,所有的對(duì)象從技術(shù)上講也只不過(guò)是函數(shù)。這里的“
”是HTML中的元素,稱之為DOM,在這里起的是換行的作用,我們會(huì)在稍后介紹它,這里我們先關(guān)心下this。this關(guān)鍵字表示函數(shù)的所有者或作用域,也就是這里的Person。
上面的方法顯得有點(diǎn)不可取,換句話說(shuō)和一開(kāi)始的
document.write(3*4);
一樣,不具有靈活性,因此在我們完成功能之后,我們需要對(duì)其進(jìn)行優(yōu)化,這就是程序設(shè)計(jì)的真諦——解決完實(shí)際問(wèn)題后,我們需要開(kāi)始真正的設(shè)計(jì),而不是解決問(wèn)題時(shí)的編程。
var Person=function(name,weight,height){
this.name=name;
this.weight=weight;
this.height=height;
this.future=function(){
return "future";
};
};
var phodal=new Person("phodal",50,166);
document.write(phodal.name+"
");
document.write(phodal.weight+"
");
document.write(phodal.height+"
");
document.write(phodal.future()+"
");
于是,產(chǎn)生了這樣一個(gè)可重用的Javascript對(duì)象,this關(guān)鍵字確立了屬性的所有者。
3.4 其他
Javascript還有一個(gè)很強(qiáng)大的特性,也就是原型繼承,不過(guò)這里我們先不考慮這些部分,用盡量少的代碼及關(guān)鍵字來(lái)實(shí)際我們所要表達(dá)的核心功能,這才是這里的核心,其他的東西我們可以從其他書(shū)本上學(xué)到。
所謂的繼承,
var Chinese=function(){
this.country="China";
}
var Person=function(name,weight,height){
this.name=name;
this.weight=weight;
this.height=height;
this.futrue=function(){
return "future";
}
}
Chinese.prototype=new Person();
var phodal=new Chinese("phodal",50,166);
document.write(phodal.country);