十六 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()();

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容