【javascript】this

1、函数预编译过程 this -->window

2、全局作用域里this -->window

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

4、obj.func();  func()里面的this指向obj

5、例题:

(1)          var f = (
                function f() {
                    return "1";
                },
                function g() {
                    return 2;
                }
            )();
            typeof f;    //结果为‘number,括号里用逗号分隔,取后面那个
2)     var x = 1;
            if(function f() {}) {
                x += typeof f;
            }
            console.log(x);    //结果‘1undefined’


(3){} == {}  -->false      因为{} 为两个不同的空间

(
4) 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(); } } b.say(a.say); // 222 // b 的say 里面的this指向b, 但函数并没有谁调用它执行,所以函数里面this,指向window b.say = a.say; b.say(); // 333 (5) var foo = 123; function print() { //var this = Object.create(print.prototype)   this.foo = 234; //这里的this 没有foo ,所以就上上一层找          console.log(foo); // 123        }        new print(); (6)    var a = 5; function test() {           a = 0;           alert(a); //0           alert(this.a); //undefined this 上面没有a           var a;           alert(a); //0        }      new test(); AO{ a : 0, this : {} }

 

posted @ 2020-02-08 20:46  shumeihh  阅读(96)  评论(0编辑  收藏  举报