一、全局作用域中的this
es5,6,不管是严格模式函数不是严格模式this都指向window
// 'use strict'; console.log(this); //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
二、全局作用域中函数中的this
es5,非严格模式this指向window,严格模式this指向undefined;es6箭头函数的this都指向window
//es5,非严格模式 // function demo() { // console.log(this); // } // demo(); //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} //es5,严格模式 // function demo() { // 'use strict'; // console.log(this); // } // demo(); //undefined //es6,非严格模式 // let demo = () => { // console.log(this); // } // demo(); //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} //es6,严格模式 // let demo = () => { // 'use strict'; // console.log(this); // } // demo(); //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
三、 对象的函数(方法)中的this
es5,不管是严格模式还是非严格模式,this的指向都是调用这个函数的对象;es6的this则是执行该对象所处的执行上下文(执行环境)
//在window执行上下文中 //es5,非严格 // var obj = { // fun: function () { // console.log(this); // } // } // obj.fun(); //{fun: ƒ} //es5,严格 // var obj = { // fun : function () { // 'use strict'; // console.log(this); // } // } // obj.fun(); //{fun: ƒ} //es6,非严格 // var obj = { // fun: ()=>{ // console.log(this); // } // } // obj.fun(); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} //es6,严格 // var obj = { // fun: ()=>{ // 'use strict'; // console.log(this); // } // } // obj.fun(); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} //在一个函数内 //es5,非严格 // function Constructor() { // var obj = { // fun : function () { // console.log(this); // } // } // obj.fun(); //{fun: ƒ} // // } // // Constructor(); //es5,非严格 // function Constructor() { // var obj = { // fun : function () { // 'use strict'; // console.log(this); // } // } // obj.fun(); //{fun: ƒ} // // } // // Constructor(); //es6,非严格 // function Constructor() { // var obj = { // fun: () => { // console.log(this); //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} // } // } // obj.fun(); // } // Constructor(); //es6,严格 // function Constructor() { // var obj = { // fun: () => { // 'use strict'; // console.log(this); //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} // } // } // obj.fun(); // } // Constructor();
四、构造函数的this
在严格模式下,构造函数中的this指向构造函数创建的对象实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
五、事件处理函数中的this
在严格模式下,在事件处理函数中,this指向触发事件的目标对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
六、内联事件处理函数中的this
在严格模式下,在内联事件处理函数中,有以下两种情况:
1 2 3 4 5 6 7 8 9 |
|