javascript - this

 1 /**
 2  * this默认指向全局
 3  * 单独执行 -> 全局变量(一旦对象被window引用,也是成全局)
 4  */
 5 // console.log(this);
 6 
 7 // 当然->这也是指向全局的
 8 function thatThis(x, y) {
 9     this.x = x;
10     this.y = y;
11 }
12 
13 
14 // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
15 
16 
17 
18 /**
19  * 改变this指向
20  * 
21  * 作者:LuckyJing
22  * 链接:https://www.jianshu.com/p/796e903754f1
23  * 來源:简书
24  * 简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
25  */
26 function alterThis() {
27     var object = {
28         name: "My Object",
29         getNameFunc: function () {
30             // 改变this引用.
31             var that = this;
32             console.log(that);
33             // return function () {
34             //     return that.name;
35             // };
36         }
37     };
38 }
39 // obj环境执行 -> 本身
40 alterThis();

 

详情见阮一峰this

posted @ 2018-09-03 10:30  Sunsin  阅读(207)  评论(0编辑  收藏  举报