https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this
https://www.runoob.com/js/js-strict.html
https://www.jb51.net/article/118506.htm
use strict
严格模式下,在全局作用域中,this指向window对象
- 全局作用域中的 this,指向 window
- 函数中的 this,等于 undefined
- 对象的函数(方法)中的this,指向调用函数的对象实例
- 构造函数的this,指向构造函数创建的对象实例
- 事件处理函数中的this,事件处理函数中,this指向触发事件的目标对象
- 内联事件处理函数中的this
"use strict";
console.log("this === window", this === window); // true
function fn(){
console.log(this); // undefined
}
var obj = {
a: 'o.a',
f5: function(){
return this.a;
}
}
function Person() {
this.a = 'ok';
this.fn = function() {
console.log(this.b) // this指向构造函数创建的对象实例
return this.a
}
}
var obj = new Person()
obj.b = 'obj.b'
console.log(obj.fn())
function onClick(e){
if(this === e.target){
// p段落
this.style.backgroundColor = "#00f";
}
}
var elements = document.getElementsByTagName('p');
for(var i=0 ; i < elements.length ; i++){
elements[i].onclick = onClick
}
// undefined
<button onclick="alert((function(){'use strict'; return this})());">
内联事件处理1
</button>
// button
<button onclick="'use strict'; alert(this.tagName.toLowerCase());">
内联事件处理2
</button>