e 2 weeks ago
parent
commit
a090cfb0f9
2 changed files with 81 additions and 0 deletions
  1. 45 0
      3.js初级/DOM/20.this指向.html
  2. 36 0
      3.js初级/DOM/21.修改this指向.html

+ 45 - 0
3.js初级/DOM/20.this指向.html

@@ -0,0 +1,45 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+    <style>
+        #box1 {
+            width: 200px;
+            height: 200px;
+            background: #f00;
+        }
+    </style>
+</head>
+<body>
+    <div id="box1"></div>
+    <script>
+        var box1 = document.getElementById("box1");
+        // 1.点击事件 this指向对象本身
+        // box1.onclick = function() {
+        //     console.log(this)
+        // }
+        // 2.定时器 指向全局window
+        box1.onclick = function() {
+            setInterval(function() {
+                console.log(this)
+            },1000)
+        }
+        // 3.对象中的this 指向对象本身
+        var obj = {
+            name:"Lucy",
+            age:18,
+            address:function() {
+                console.log(this)
+            }
+        }
+        obj.address()
+        // 4.函数中this 指向window
+        function fn1() {
+            console.log(this,'函数')
+        }
+        fn1()
+    </script>
+</body>
+</html>

+ 36 - 0
3.js初级/DOM/21.修改this指向.html

@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+</head>
+<body>
+    <script>
+        function fn1(x,y) {
+            var sum = x * y;
+            console.log(sum,'sum')
+            console.log(this,'this')
+            console.log(this.name)
+        }
+        var obj = {
+            name:"LiLi"
+        }
+        fn1(2,3)
+        // fn1.call(obj,2,3)
+        // fn1.apply(obj,[2,3])
+        fn1.bind(obj,2,3)()
+        /**
+         * 修改this指向
+         * 1.call(修改的this指向,参数1,参数2,.....) 
+         * 2.apply(修改的this指向,[参数1,参数2,.....])
+         * 3.bind(修改的this指向,参数1,参数2,.....)()
+         * 区别:
+         * 1.bind无法进行函数直接调用,call和apply可以进行函数直接调用
+         * 2.call从第二项开始就是要传入的参数
+         * 3.apply从第二项开始,所有参数放到数组中
+         * 4.call的传参与bind相同
+         */
+    </script>
+</body>
+</html>