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