| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <!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>
- <button id="btn">点击我</button>
- <script>
- // this 指向问题 this一般指向调用它的对象
- // 如果有事件绑定,this指向事件绑定的对象
- let btn = document.getElementById("btn");
- btn.onclick = function(){
- // function bar(){
- // console.log(this);
- // }
- // bar();
- let bar = () => {
- console.log(this);
- }
- bar();
- console.log(this);
- }
- // 普通函数中 this指向window对象 默认为winow调用
- // function foo(){
- // console.log(this);
- // // 内部函数中 this指向window对象
- // function bar(){
- // console.log(this);
- // }
- // bar();
- // }
- // foo();
- // let obj = {
- // name:"张三",
- // age:18,
- // sex:"男",
- // sayName(){
- // console.log(this);
- // // function bar(){
- // // console.log(this);
- // // }
- // // bar();
- // // 箭头函数中 this指向为当前所在作用域的this (箭头函数中没有this)
- // let bar = () => {
- // console.log(this);
- // }
- // bar();
- // }
- // }
- // obj.sayName();
- // this 指向是可以被修改的 通过call、 apply、 bind 方法可以修改this指向
- var userName = "李四"
- var obj = {
- userName:"张三",
- age:18,
- sex:"男"
- }
- function sayName(word){
- console.log(this.userName+"说"+word);
- }
- // call 方法可以修改this指向为obj对象 要执行的函数.call(修改后的this对象,参数1,参数2...)
- // sayName.call(obj);
- // sayName("你好");
- // 如果函数需要接收参数 call方法中从第二个参数开始传递参数
- // sayName.call(obj,"你好");
- // apply 方法可以修改this指向为obj对象 要执行的函数.apply(修改后的this对象,参数数组)
- // sayName.apply(obj,["你好"]);
- // bind 方法可以修改this指向为obj对象 要执行的函数.bind(修改后的this对象,参数1,参数2...)
- // bind 方法返回一个新的函数 并不是立即执行函数
- let bar = sayName.bind(obj,"你好");
- bar();
- </script>
- </body>
- </html>
|