javascript 常见的this指向

一、指向window,即全局对象

1 this
2 //Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
 1 var a =12;
 2 
 3 function (){
 4 console.log(this.a);
 5 }
 6 
 7 function aaa(){
 8 console.log(this.a);
 9 }
10 
11 aaa();
12 12

 

 

二、指向构造函数的实例化对象

1 function Page(url,name){
2  this.url=url;3  this.name = name;6 }
7 
8 var page1 = new Page("https://i.cnblogs.com","blogs");
page1.url;
// "https://i.cnblogs.com/"

 

三、使用Apply或call,指向调用它的第一个参数

1 function foo() {
2    console.log( this.a );
3 }
4 var obj = {
5    a:2
6 };
7 foo.call( obj );
8 // 2

 四、指向调用方法的对象

1 function test(){
2    console.log(this.x);
3   }
4   var o = {
5 x : 3
6 };
7 o.m = test;
8 o.m();
9 // 3

 

posted @ 2016-08-24 15:27  bentos  阅读(202)  评论(0编辑  收藏  举报