十六 this

函数预编译过程

        this --> window

全局作用域

        this --> window

call / apply 可以改变函数运行时的this指向

谁调用,this就指向谁


var name = "222";

var  a = {

            name : "111",

            say :  function ( ) {

                    console.log ( this.name ) ;

            } 

}

var  fun = a.say;

fun ( );            //  222

a.say ( );            // 111

var b = {

        name : "333",

        say : function ( fun ) {

                fun () ;      //222  这里走的是预编译的环节,没有被调用,不用考虑this指向

                this.fun();  //333

        }

}

 b.say ( a.say );     // 222

b.say = a.say;

b.say ( ) ;        //333


var foo = 123;

function print(){

  //new的时候, var this = Object.create( print.prototype );

 //不new就走预编译

        this.foo = 234;

        console.log( foo );

}

print();   // 234

new print(); //123


var bar = { a:"002"}

function print (){

    bar.a = "a";

    Object.prototype.b = 'b';  

    return function inner(){

        console.log( bar.a );   // a

        console.log( bar.b );  // b

    }

}

print()();

你可能感兴趣的:(十六 this)