练习题2_this指向.html 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script>
  11. //1、写出下列输出结果
  12. var x = 10;
  13. function test(){
  14.   this.x = 20
  15.   console.log(this.x)
  16. }
  17. test()
  18. //2、写出下列输出结果
  19. var name= "window"
  20. var obj = {
  21. name:"obj",
  22. func1 : function() {
  23. console.log(this.name);
  24. (function(){
  25. console.log(this.name)
  26. })()
  27. }
  28. }
  29. obj.func1()
  30. //3、写出下列结果
  31. var name="the window";
  32. var object={
  33. name:"My Object",
  34. getName:function(){
  35. return this.name;
  36. }
  37. }
  38. console.log(object.getName());
  39. console.log((object.getName)());
  40. console.log((object.getName=object.getName)());
  41. //4、下列代码中当div的点击事件触发时输出的结果是?
  42. document.getElementById("div").onclick = function(){
  43. console.log(this)
  44. };
  45. //5、请写出下列代码运行结果
  46. var name = "window"
  47. var obj = {
  48. name:"obj"
  49. }
  50. window.setInterval(function(){
  51. console.log(this.name)
  52. }, 300)
  53. window.setInterval(function(){
  54. console.log(this.name)
  55. }.call(obj),300)
  56. //6、请补全下列代码
  57. function foo(){
  58. //补全此处代码实现每隔一秒输出 hello world
  59. }
  60. window.setInterval(foo(),1000);
  61. // 7、补全下列代码实现 1+2+3+4
  62. function add(c, d) {
  63. return this.a + this.b + c + d;
  64. }
  65. /*
  66. 在此补全代码 以两种以上方法实现
  67. */
  68. //8、写出下列输出结果
  69. function f(){
  70. return this.a;
  71. }
  72. var g = f.bind({a:"azerty"});
  73. console.log(g());
  74. var h = g.bind({a:'yoo'});
  75. console.log(h());
  76. var o = {a:'loveCoding', f:f, g:g, h:h};
  77. console.log(o.f(), o.g(), o.h());
  78. //9、补全下列代码
  79. var o = {prop: 'loveCoding'};
  80. function independent() {
  81. return this.prop;
  82. }
  83. //在此补全代码
  84. console.log(o.f()); // loveCoding
  85. //10、用call 或 apply 实现bind 方法
  86. function foo(){
  87. console.log(this.a)
  88. }
  89. var obj = {
  90. a:"hello"
  91. }
  92. var foo2 = foo.bind2(obj);
  93. foo2()//hello
  94. </script>
  95. </body>
  96. </html>