zoukankan      html  css  js  c++  java
  • js中 this的指向,如果工作

    <script>
    function fun() {
    console.log(this)
    }

    fun() // Window

    let obj = {
    a:fun
    }

    obj.a() // obj

    function test2(c) {
    c&&c()
    }
    test2(obj.a) // Window
    // 怎么改变为指向obj?
    test2(obj.a.call(obj)) // obj
    test2(obj.a.bind(obj)) // obj
    test2(obj.a.apply(obj)) // obj
    </script>

    <script>
    class Test {
    fun = () => {
    console.log(this);
    };

    fun1() {
    console.log(this);
    }
    }

    let test = new Test();
    test.fun(); // Test
    console.log(this) // Window
    test.fun.call(this); // Test 为啥不是win,原因箭头函数没有this,剪头函数的this是继承父执行上下文里面的this ,

    test.fun1() // Test

    test.fun1.call(this) // Window
    </script>

    <script>
    var person = {
    fullName: function() {
    return this.firstName + " " + this.lastName;
    }
    }
    var person1 = {
    firstName:"John",
    lastName: "Doe",
    }
    var person2 = {
    firstName:"Mary",
    lastName: "Doe",
    }
    console.log(person.fullName.call(person2)) // 将返回 "Mary Doe"
    </script>

    <script>
    var x = 11;
    var obb = {
    x: 222,
    y: {
    x:333,
    obc: function f() {
    console.log(this)
    var x = 111;
    var obj = {
    x: 22,
    say: () => {
    console.log(this.x);
    }
    }
    obj.say()
    }
    }
    }
    obb.y.obc() // 333
    </script>

    js箭头函数的this指向:

    https://blog.csdn.net/weixin_42519137/article/details/88053339

    全面的JS this指向问题 以及如何改变this 指向的方法(call、apply、bind区别)适合初学者的一篇文章

    https://blog.csdn.net/weixin_42207353/article/details/104909252

  • 相关阅读:
    Socket通信中的多进程编程(TCP/IP通信过程)
    AsyncSocket.h解读
    AsyncSocket编程
    命令行下文件名空格的处理
    socket编程 Asyncsocket (转)
    iPhone网络编程初体验简单的聊天程序 (转)
    2.0版本cocos2diphone 开发之CCProgressTimer制作游戏中的血条
    js 旋转图片
    css图片旋转
    数据结构之单向链表
  • 原文地址:https://www.cnblogs.com/plBlog/p/14004624.html
Copyright © 2011-2022 走看看