天天看點

JAVAScript ~Function對象

<!--Function對象 -->

<html>

    <head>

        <meta charset="utf-8">

        <title>Function對象</title>

    <script type="text/javascript">

         //一.①這個方法不怎麼常見

        var sum =new Function("x","y","return(x+y)");

        //②一般使用第二種

        function sum(x,y){

            return (x+y);

        }

        //③函數在JAVAScript有很多功能,他可以看成一個類的申明,函數本身就是一個構造器。列如:

        function Cat(name,color){

            this.name=name;

            this.color=color;          

            this.eat=function(){alert(this.color+this.name+"吃老鼠")}

        }

        var cat=new Cat("貓咪","黃色");

        cat.eat();

       var Animal={

           createNew: function(){

               var animal={};

               animal.sleep=function(){alert("睡懶覺");};

               return animal;

           }

       };

       var Cat={

           createNew:function(){

               var cat=Animal.createNew();//傳回一個Animal對象,存在cat中

               cat.name="貓咪";

               cat.makeSound=function(){alert("喵喵");};

           return cat;

           }

       };

       var cat1=Cat.createNew();

       cat1.sleep();

       cat1.makeSound();

       //2.使用prototype

        function Animal1(){

            this.sleep=function(){alert("睡覺");};            

        }

        function Dog(){

            this.name="小狗";

        }

        Dog.prototype=new Animal1();//讓Dog繼承Animal1;

        var dog=new Dog();//建立Dog對象

        Dog.prototype.type="犬類";//給Dog添加屬性

        Dog.prototype.newMethod=function(){alert(this.type);}//給dog類添加新的方法

        dog.sleep();

        dog.newMethod();

         alert(dog.name);

    </script>

    </head>

    <body>

    </body>

</html>

繼續閱讀