1. var name = "张三"
  2. function show(){
  3. console.log(this.name)
  4. }
  5. /* 函数正常调用的时候this指向window */
  6. function go(){
  7. var name = "李四"
  8. show();
  9. }
  10. window.go();
  11. /* 函数要有对象去调用,事件也是需要对象去执行的 */

1-1 call,applay

  1. /* call 可以改变函数内部this关键字的指向 funName.call(obj) */
  2. /* applay funName.applay(obj) */
  3. var name = "王五";
  4. var obj = {
  5. name:"李四"
  6. }
  7. function go(){
  8. console.log(this.name)
  9. }
  10. go();
  11. go.call(obj);
  12. go.apply(obj);

1-2 call和apply之间的区别

  1. /*
  2. 应用场景:传递多个参数的情况
  3. call 依次去传递
  4. applay 需要传递数组
  5. */
  6. var name = "window"
  7. var zhang = {
  8. name: "张三"
  9. }
  10. function show(a, b) {
  11. console.log(this.name);
  12. console.log(a + b)
  13. }
  14. // show(1,2)
  15. // show.call(zhang,2,3);
  16. show.apply(zhang,[1,2])
  17. </script>

1-3 bind

  1. /*
  2. bind绑定的函数不会马上执行,只是改变了函数上下文的执行环境
  3. call,applay调用的时候马上执行
  4. */
  5. var name = "window"
  6. var zhang = {
  7. name: "张三"
  8. }
  9. var show = function(a,b){
  10. console.log(this.name)
  11. console.log(a+b);
  12. }.bind(zhang);
  13. show(2,3);

1-3-1 应用场景

  1. <button id="btn">按钮</button>
  2. <script>
  3. var id = "1001"
  4. var btn = document.getElementById("btn");
  5. btn.onclick = function(){
  6. setTimeout(function(){
  7. console.log(this.id)
  8. },1000)
  9. }
  10. </script>
  11. # 定时器在事件中,还是window在调用的定时器,所以this指向window,输出"1001"

可以使用**bind**解决this关键字指向问题

  1. <button id="btn">按钮</button>
  2. <script>
  3. var id = "1001"
  4. var btn = document.getElementById("btn");
  5. btn.onclick = function(){
  6. setTimeout(function(){
  7. console.log(this.id)
  8. }.bind(btn),1000)
  9. }
  10. </script>
  1. <button id="btn">按钮</button>
  2. <script>
  3. var id = "1001"
  4. var btn = document.getElementById("btn");
  5. btn.onclick = function(){
  6. setTimeout(function(){
  7. console.log(this.id)
  8. }.bind(this),1000)
  9. }
  10. </script>

也可以使用箭头函数

  1. btn.onclick = function(){
  2. setTimeout(function(){
  3. console.log(this.id)
  4. }.bind(this),1000)
  5. }