Function 在 中是一個很特殊的對象,其特殊性體現在它的多重身份。
Function 可以聲明普通的函數,這一點和其他語言中的函數概念是相同的。除此以外,Function還可以用作類型的聲明和實現、對象的建構函式,以及類引用。
Apply和Call方法可以將函數綁定到其它對象上執行。
使用for(…in…)語句可以遍曆對象的所有屬性和方法。如下面的例子就遍曆了test1對象的屬性和方法,如果是屬性剛輸出屬性,如果是方法剛執行方法。
function test1()
{
this.p1="p1";
this.p2="p2";
this.f1=function()
{
alert("f1");
}
this.f2=function()
{
alert("f2");
}
}
var obj1=new test1();
//遍曆t的所有屬性
for(p in t)
{
//如果是函數類型剛執行該函數
if(typeof(t[p])=="function")
t[p]();
//輸出其它類型的屬性
else alert(t[p]);
}
1. 類的聲明
(1)、使用this關鍵字
function test1()
{
this.p1="p1";
this.p2="p2";
this.f1=function()
{
alert("f1");
}
this.f2=function()
{
alert("f2");
}
}
在中,成員變數沒有私人與公有機制,但可以通過在類內部使用var來聲明局部變數。其範圍是類定義的內部。
(2)、使用ptototype方式的類聲明
如果要聲明一個類的執行個體屬性或方法,可以使用中的對象的prototype屬性。例如:
Test1.prototype.prop2=”prop2”;
Test1.prototype.method2=function(){
Alert(this.prop2);
}
使用prototype屬性聲明類,如下
function test()
{
}
test.prototype={
p1:"p1";
p2:"p2";
f1 : funciton ()
{
alert("f2");
}
}
2. 繼承
本身並沒有提供繼承的文法支援,但是在仍然可以採用複製屬性和對象的方法實現繼承。
function test2(){}
for(p in test.prototype)
{
test2.prototype[p]=test.prototype[p];
}
test2.prototype.newMethod=function()
{
alert("newMethod");
}
另外可以參考Prototype架構實現繼承的方法:
object.extend=function (destination,source)
{
for(property in source)
{
destination[property]=source[property];
}
return destiantion;
}
function test2() {}
test2.prototype=object.extend ({newMethod :function ()
{alert (“newMethod”);}
},
Test.prototype
);
3. 多態
多態的實現可以採用和繼承類似的方法。首定義一個抽象類別,其中可以,調 用一些虛方法,虛方法在抽象類別中沒有定義,而是通過其具體實作類別來實現的。例如:
object.extend=function (destination,source)
{
for(property in source)
{
destination[property]=source[property];
}
return destiantion;
}
//定義一個抽象基類
function base() {}
base.prototype={
initialize:function(){
this.oninit();//調用了一個虛方法
}
}
function test()
{
//建構函式
}
test.prototype=object.extend(
{
prop:"prop",
oninit :function()
{
alert(this.prop)
}
},base.prototype
);
function test2()
{
}
test2.prototype=object.extend(
{
prop2: "prop2";
oninit:function()
{
alert(this.prop2);
}
},base.prototype
}