一对一聊天源码,this指向问题

一对一聊天源码,this指向问题

不同开发法环境下全局环境中this指向

提示: this 的指向是在代码运行时,被动态绑定的。

浏览器中下全局环境的 this 指向 window

//测试
console.log(this);      // window

node 中全局环境的 this 指向 global

//测试
console.log(this)       // global

“use strict” 严格模式下全局环境的 this 指向 undefined

"use strict"

// 测试
console.log(this)      // undefined

谁调用 this 就指向谁

函数在全局环境中自行调用时函数中 this 指向全局环境中 this 指向的对象
注意: 全局环境中的函数自行调用类似于被全局环境中 this 指向的对象所调用(如:window.F())

let name = "Jason"
function getName() {
    console.log(this.name);
}

1. 浏览器中
getName()       // Jason, this -> window
// 类似于
window.getName()

3. node 环境中
getName()       // Jason, this -> global
// 类似于
global.getName()

3. 严格模式中
"use strict" 
getName()       // undefined, this -> undefined
// 类似于
undefined.getName()

对象中的方法在被对象调用时 this 指向调用它的对象

let user = {
    name: "Jason",
    getName: function(){
        console.log(this);
        console.log(this.name);
    },
    obj: {
        age: 23,
        getAge: function(){
            console.log(this);
            console.log(this.age);
        }
    }

}

// 测试
user.getName()          // user Jason, this -> user
user.obj.getAge()       // obj 23, this -> obj

构造函数中的 this 指向构造函数的实例对象

function User(name, age) {
    this.name = name;
    this.age = age;
}
User.prototype.getUser = function(){
    console.log(this)
}

// 测试
let user = new  User("Jason", 23)
user.getUser();// this 指向构造函数实例, this -> user

setTimeout, setInterval 中的 this 指向全局中的 this

let F = ()=> {
    setTimeout(function(){
        console.log(this)
    },2000)
}
// 测试
F();        // window, this -> window
Class 中的 this 指向类实例的对象
class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    getUser(){
        console.log(this.name);
        console.log(this.age);
        console.log(this);
    }
}

// 测试
let user = new User("Jason", 23);
user.getUser()      // Jason 23, this -> user

箭头函数中没 this, 如果箭头函数中使用 this 的话, this 指向取决于外层对象或函数的 this 指向

setTimeout(()=>{
    console.log(this);
},3000)
// this -> windeow, 箭头函数中的 this 指向取决于 setTimeout 的 this 指向

以上就是一对一聊天源码,this指向问题, 更多内容欢迎关注之后的文章

posted @ 2025-11-22 09:54  云豹科技-苏凌霄  阅读(5)  评论(0)    收藏  举报