JavaScript的call、apply、bind

 <script>
 
 // let a = {
 //     name : "懶羊羊",
 //     fn : function(){
 //         console.log(this.name);
        //     }
        // }
        // let b = a.fn;
       // b.fn();  爲空
    //    call、apply的做用
    // 一、執行函數;二、改變this指向 三、能夠傳參數
    //call 傳參:第一個參數是this的指向,
    //後面的參數都是 對應b函數的形參
    
    // let a = {
    //         name : "懶羊羊",
    //         fn : function(){
    //             console.log(this.name);
    //         }
    // }
    // let b = a.fn;
    // b.apply(a,["美美的","美羊羊"]);
 
    
    // let a1 = {
    //         name : "fei羊羊",
    //         fn : function(){
    //             console.log(this.name);
    //         }
    // }
    // let b1 = a1.fn;
    // b1.apply(a1,["美美的","美羊羊"]);

    //三、bind
    //做用:能夠改變this指向,二、能夠傳入參數,三、不能夠執行函數,返回一個新函數

    let a = {
            name : "懶羊羊",
            fn : function(adj, person){
                console.log(this.name + adj + person);
            }
    }
    let b = a.fn;
    // b.bind(a,["美美的","美羊羊"]);  //什麼也沒有
    let c = b.bind(a ,"美美的","美羊羊");
    // b.bind(a,"美美的","美羊羊")();
    // b.bind(a,"美美的")("美羊羊");
    // b.bind(a)("美美的","美羊羊");  //能夠減小一下重複參數
    //方式1、2、三
    c();
    
    //區別:call和apply立馬執行函數  bind不能執行函數,返回一個新函數
    //相同:都能改變this指向   均可以傳參數
        //寫一個源碼  new的實現

 

        // function Beatifulsheep(){
        //     this.name = name,
        //     this.age = age,
        //     this.sec = sex
        // }
        // Beatifulsheep.prototype.sing = function(){
        //     console.log(this.name + "說,我會唱歌");
        // }
        // Beatifulsheep.prototype.cook = function(){
        //     console.log(this.name + "說,我會作飯");
        // }
        // let myy = new Beatifulsheep("美羊羊","22","女");
        // myy.sing();
        // myy.cook();

 

        //new的做用
        // 一、生成一個實例對象 (而且把函數內部的thia 指向實例對象)
        //二、運行改構造函數 初始化裏面的屬性賦值
        //三、把實例對象的原型鏈指向構造函數的原型對象

 

        //一、能夠訪問構造函數的屬性
        //二、能夠訪問原型上的屬性



        //一、能夠訪問構造函數的屬性
        // function Person(){
        //     this.name = ["1",["2"]];
        // }
        // function child(){
        //     Person.call(this);
        // }
        // let c = new child();
        // c.name.push("111");
        // console.log(c.name);

 

        //二、能夠訪問原型上的屬性
        // function Person(){
        //     this.name = ["1",["2"]];
        // }
        // function child(){
        //     Person.call(this);
        // }
        // let cc = new child();
        // cc.protety = Person.protety;
 

 

    </script>
相關文章
相關標籤/搜索