2011年3月28日 星期一

物件原型 prototyping

1.prototype是Object的屬性,每一個javascript的物件都有這個屬性。

你可以利用它擴展物件的屬性和方法

包括String、Number這些基礎型別

    例一( 以javascript本生的基礎型別示範 ):

        替String加一個method : trim( )
        //用來去掉字字串前後的空白

        String.prototype.trim=function()
        {
            return (this.replace( /^[\s\xA0]+/ , "" ).replace( /[\s\xA0]+$/,""));
        }

        var sObj=new String("    This is the string      ");

        sTet=sObj.trim();

        document.writeIn("__"+sTet+"__");

     例二(自訂物件的原型範例)

        在javascript中,自訂一個function就是撣於建立一個物件

        function someObject ( ) 
        {
            this.method1=objMethod1;
        }
        function objMethod1( ) 
        {
            ....
        }
        //容易了解的寫法

        鏈式建構函式(chaining constructor)

        function Tune( title )
        {
            this.title=title;
        }
        //定義Tune物件

        function    printTitle ( )
        {
            alert(this.title);
        }
        //定義Tune物件要指派的print方法   printTitle 方法
        
        var someTune=new Tune("Title");
        Tune.prototype.print = printTitle;
        
        //使用Tune物件
        //指定Tune的prototype屬性會有一個print方法,並且把剛剛定義好的printTitle方法指派給他

        ----------定義完畢-----------

        var anotherTune = new Tune( " Another " );

       anotherTune.print( )

2."this"指向問題:

        在物件(Object)內指定一個屬性(prorerty)用
                        
        var someObj=
                            {
                                this.屬性=OO;
                                //代表public公開的(外部可直接存取)
                                var 屬性=OO;
                                //代表私有的,要開get或是set  method
                            }
3.物件偵測

範例一:

var opacity=1.0;
//必須先指定值給他
var img1=document.onclick=adjustOpacity;


function adjustOpacity ( )
{
    opacity=opacity-0.1;
    //這個函式要對
    var img=document.getElementById("img1");
    //把文件上的img1指派給一個物件

    if(img1.style.filter)
    //假使是IE就是filter(濾鏡)
    {
        var opac = opacity * 100;
        //濾鏡是100分之幾
        img1.style.filter="alpha( opacity:"+opac+")";
        
    }
    else if(img1.style.opacity)
    {
        img1.style.opacity=opacity;
    }
    else
    {
        alert("Opacity not supported")
    }
}

4.封裝 ( encapsulation )

        把兩個執行的動作各存到一個method裡

5.複雜的call( )和apply( )

基本上是一樣的東西

你可以想像把一個物件增加了其他物件的屬性和方法

這樣解釋成繼承(inheritance)


PS:指名function ( metod ) 的兩種定義方式

1.直接定義

function test(){}

2.指派

var test=function(){}


都叫做test ( )

function tune(title,type)
{
    this.title=title;
    this.type=type;
    this.getTitle=function()
    {
        return "Song:  "+this.title+ "  "+this.type;
    }
}

function artist_tune(title,type,artist)
{
    this.artist=artist;
    this.toString("Artist is "+artist);
    tune.apply(this,drgument);
    this.toString=function()
    {
        return "Artist: "+this.artist+ " " +this.getTitle; 
    }
}

artist_tune.prototype=new tune( );

call( )和apply()的差異在於

call(this,arg1物件1,arg2物件2,arg3物件3,...)

apply(this,arguments)

沒有留言:

張貼留言