不少人都會被JavaScript中this的指向(也就是函數在調用時的調用上下文)弄暈,這裏作一下總結:javascript
首先,頂層的this指向全局對象。java
函數中的this按照調用方法的不一樣,其指向也不一樣:瀏覽器
一、函數調用中的this指向全局對象app
二、方法調用的函數中的this指向調用函數的對象:函數
function AnObject(name){ this.name = name; this.getThis = function(){ console.log(this); } } var ob = new AnObject('test'); ob.getThis(); //AnObject {name: "test"}這裏方法getThis被對象ob調用,故這裏的this指向ob對象{name: "test"};
function getThis(){ console.log(this); } getThis(); // Window console.log(window.getThis); //function getThis(){......}這裏getThis是直接在頂層做用域下定義的一個方法,這裏的this返回全局對象Window。咱們都知道全局變量實際上是做爲全局對象的屬性來實現的,這裏的函數也是如此。用function getThis(){......}的寫法等同於 var getThis = function() {......}。
而關於」頂層的this指向全局對象「,個人我的理解是: 頂層的代碼段能夠理解爲全局做用域下的一個匿名函數,暨全局對象的一個方法,執行完畢後就銷燬。那麼這個方法中的this天然指向全局對象了。在REPL或者瀏覽器的控制檯交互中,咱們均可以感覺到這樣的性質。this
三、構造函數中的this指向新建立的對象
spa
function AnObject(name) { this.name = name; console.log(this); } var ob = new AnObject('another test');// AnObject {name: "another test"}
function AnObject(name){ this.name = name; this.getThis = function(){ console.log(this); } } var ob = new AnObject('test'); ob.getThis.call({name: ' surprise '}); //Object {name: " surprise "} ob.getThis.apply({name: ' surprise '});//Object {name: " surprise "} var a = ob.getThis.bind({name: ' surprise '}); a(); //Object {name: " surprise "}爲了化簡,這裏忽略了」參數列表「這個參數,僅僅傳入了新的做用域。能夠看到,這時this的指向是咱們所指定的對象。