1.方法调用
var obj = { name : "Nick", setSex : function () { console.log(this);//obj console.log(this.name);//Nick } }; obj.setSex();
2.apply 调用
1 var book = { 2 3 }; 4 5 function getBookName(name){ 6 console.log(this);//book 7 console.log(name);//hehe 8 } 9 10 getBookName.apply(book,["hehe"]);
3.构造函数调用
1 function Book(){ 2 this.title = "read"; 3 console.log(this); 4 console.log(this.title); 5 } 6 Book.prototype.dosth = function() { 7 // body... 8 console.log(this); 9 console.log(this.title); 10 }; 11 Book.dosth2 = function(){ 12 console.log(this); 13 console.log(this.title); 14 }; 15 var book = new Book(); 16 book.dosth(); 17 Book.dosth2(); 18 //Book内部以及原型链上的this指代了Book对象,而Book添加的函数dosth2里面this指代为Book这个函数
4.函数调用
1 function getThis (){ 2 console.log(this);//window 3 } 4 getThis();