1. 程式人生 > >JS apply與call

JS apply與call

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>apply與call</title> </head> <body>     <script type="text/javascript">         function f1(){                           console.log("make it easy:" +this);         }

        console.dir(f1);         // 呼叫函式         // f1();         // f1.call();  //f1.call();  windows         // f1.apply(null);

        var obj = {             name:"小紅",             age:19,             sayHi:function(){                 console.log("我是物件:"+this );             }

        }                  f1.call(obj);//引數傳遞為obj,會使this的指向改變。原本this指向window 現在this指向obj物件。         // f1.apply(obj);         //          

        //分析建構函式繼承屬性                  function Person(age,sex){             this.age = age;             this.sex = sex;         }

        function Student(name,age,sex){             this.name = name;

            //當將當前的例項物件傳遞進去的時候,Person建構函式的中的this,指向Student 的例項物件。             //由於JS是一門動態型別語言,當Studen,沒有該屬性的時候會自動建立,因此為Student的例項物件建立             //age sex 屬性。因此可以起到繼承的建立物件特有屬性值。             //             // Person.call(this,age,sex);             Person.apply(this,[age,sex]);

        // call 與apply的區別在於傳入的形參有區別。第一個引數,均是物件。 call傳入的單個引數,apply傳入的陣列                  }

        var stu1  = new Student("小明",18,"man");          var stu2  = new Student("小青",18,"girl");

         console.log("name:"+stu1.name +"  age:"+stu1.age+"  sex:"+stu1.sex);

         console.log("name:"+stu2.name +"  age:"+stu2.age+"  sex:"+stu2.sex);

                //總結:當需要呼叫另一個物件的函式,可以使用apply call        //apply call 在Function 裡面的prototype裡面 

    </script> </body> </html>