ES5에서 this 바인딩

5175 단어 지식점

ES5에서 this 바인딩

<script>
    /**
     * this 
     *  , this window , apply、cal、bind this
     */
    var obj = {name:'tom'};
    function say(data){
        console.log(this,data);
    }
    say('111');//Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} "111"
    say.apply(obj,['111']);//{name: "tom"} "111"
    say.call(obj,'111');//{name: "tom"} "111"
    say.bind(obj,'111')();//{name: "tom"} "111"

    console.log(say.bind(obj,'111'));//f say(data){console.log(this,data);}
    // bind ,
    setTimeout(function(){
        console.log(this);
    },1000);//Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
    setTimeout(function(){
        console.log(this);
    }.bind(obj),1000);//{name: "tom"}
</script>

좋은 웹페이지 즐겨찾기