函數中的this,指向 函數運行時所在的對象(當前對象,而不是上層對象)。若是函數運行時沒有依賴的當前對象,則this指向最上層對象(eg: window)。
obj.fun()
中的this指向當前運行的對象obj 函數
fun 中的 this->obj ,自動指向.前的對象this
var obj ={ foo: function () { console.log(this); } }; obj.foo() // obj
new Fun()
中的this指向當前運行的對象(new出來的新實例對象)code
Fun 中的 this->正在建立的新對象,new 改變了函數內部的 this 指向,致使 this 指向實例化 new 的對象對象
function Person(name) { this.name = name; console.log(this); // Person {name: "song"} }; var person = new Person('song'); console.log(person.name);// "song"
fun()
中的this指向當前運行的對象windowip
this->最上層對象(eg: window),直接執行函數,this指向默認的最上層對象(eg: window)回調函數
function f() { console.log(this); } f() // window
沒有依賴的當前對象,默認指向windowit
this->最上層對象(eg: window),由於函數內函數,沒有調用它的對象,因此只能指向默認的額window。io
var o = { f1: function () { console.log(this); var f2 = function () { console.log(this); }(); } } o.f1() // Object // Window (沒有調用的它的對象了,因此只能指向默認的額window)
``` var o = { f1: function() { console.log(this); var that = this; var f2 = function() { console.log(that); }(); } } o.f1() // Object // Object ```
var o = { v: 'hello', p: [ 'a1', 'a2' ], f: function f() { this.p.forEach(function (item) { console.log(this.v + ' ' + item); }); } } o.f() // undefined a1 // undefined a2 // this指向window(由於函數內函數,沒有調用它的對象。)
保存下this,再爲後來用console
var o = { v: 'hello', p: [ 'a1', 'a2' ], f: function f() { var that = this; this.p.forEach(function (item) { console.log(that.v+' '+item); }); } } o.f() // hello a1 // hello a2
將this看成foreach方法的第二個參數,固定它的運行環境。function
var o = { v: 'hello', p: [ 'a1', 'a2' ], f: function f() { this.p.forEach(function (item) { console.log(this.v + ' ' + item); }, this); } } o.f() // hello a1 // hello a2
(箭頭函數沒有本身的this,this指向定義時所在的對象,而不是運行時所在的對象)
var o = { v: 'hello', p: [ 'a1', 'a2' ], f: function f() { this.p.forEach( item => { console.log(this.v + ' ' + item); }, this); } } o.f() // hello a1 // hello a2
也可以使用bind永久綁定this
var o = { v: 'hello', p: [ 'a1', 'a2' ], f: function f() { this.p.forEach(function (item){ console.log(this.v + ' ' + item); }.bind(this)); } } o.f() // hello a1 // hello a2
avaScript 提供了嚴格模式,也能夠硬性避免這種問題。嚴格模式下,若是函數內部的this指向頂層對象,就會報錯。
function f() { 'use strict' console.log(this); } f() // undefined
此時,上慄中的this爲window,這裏就爲未定義了!!!
只要函數被賦給另外一個變量,this的指向就會變,變爲新變量所在執行環境對象
var A = { name: '張三', describe: function () { return '姓名:'+ this.name; } }; var name = '李四'; var f = A.describe; f() // "姓名:李四"
此例中this爲window
沒寫完呢。。。。。。。。。。。。。。。。。。。。