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对象

  1. 全局作用域中的 this,指向 window
  2. 函数中的 this,等于 undefined
  3. 对象的函数(方法)中的this,指向调用函数的对象实例
  4. 构造函数的this,指向构造函数创建的对象实例
  5. 事件处理函数中的this,事件处理函数中,this指向触发事件的目标对象
  6. 内联事件处理函数中的this
  1. "use strict";
  2. console.log("this === window", this === window); // true
  3. function fn(){
  4. console.log(this); // undefined
  5. }
  6. var obj = {
  7. a: 'o.a',
  8. f5: function(){
  9. return this.a;
  10. }
  11. }
  12. function Person() {
  13. this.a = 'ok';
  14. this.fn = function() {
  15. console.log(this.b) // this指向构造函数创建的对象实例
  16. return this.a
  17. }
  18. }
  19. var obj = new Person()
  20. obj.b = 'obj.b'
  21. console.log(obj.fn())
  22. function onClick(e){
  23. if(this === e.target){
  24. // p段落
  25. this.style.backgroundColor = "#00f";
  26. }
  27. }
  28. var elements = document.getElementsByTagName('p');
  29. for(var i=0 ; i < elements.length ; i++){
  30. elements[i].onclick = onClick
  31. }
  32. // undefined
  33. <button onclick="alert((function(){'use strict'; return this})());">
  34. 内联事件处理1
  35. </button>
  36. // button
  37. <button onclick="'use strict'; alert(this.tagName.toLowerCase());">
  38. 内联事件处理2
  39. </button>