this指向

62 阅读1分钟
let obj = {
    myName: '张三',
    age: '11',
    run: function () {
        console.log(this.myName + '正在跑步');
        console.log(obj.myName + '正在跑步');
    }
}
// this可以访问对象本身中的属性和方法
obj.run();

let person = {
    name: 'zhangsan',
}

function fn1(content) {
    return content?.name.toUpperCase();
}

function fn(content) {
    fn1(content);
}


fn(person); // 多个函数进行改参数的传递,一环出错就是一系列影响。可以用this减少上下参数的传递

// 使用this减少上下文参数的传递,提升代码质量(减少冗余代码,有助于实现封装和隐藏对象内部状态,增强数据的安全性)
function fun1() {
    console.log("this", this)
    return this.name.toUpperCase();
}

function fun() {
    const result = fun1.call(this);
    console.log("result", result)
}

//this避免调用对象方法是显式传递对象本身做为参数
fun.call(person);


// 2.隐式绑定
let obj2 = {
    a: 1,
    bar: bar//引用foo
}

function bar() {
    console.log("bar=》this", this)
}

bar() // 默认绑定,this指向window
obj2.bar() // 隐式绑定,this指向obj2
bar.call(obj2) // 显式绑定,this指向obj2

function foo1(x, y) {
    console.log("显示绑定传参", this, x, y)
}

foo1.call(obj2, 1, 2) // 显示绑定,this指向obj2,x=1,y=2
foo1.apply(obj2, [1, 2]) // 显示绑定,this指向obj2,x=1,y=2

// new绑定  this指向创建出来的实例对象

var obj3 = {
    a: 100,
    b: function () {
        const fn = () => {
            console.log("new=>this", this.a); // new=>this 100 箭头函数没有自己的this,会从外层作用域继承this
        }

        function fn1() {
            console.log("new=>this", this.a);
        }

        fn()
        fn1() // new=>this undefined
        fn1.call(this) // new=>this 100 显示绑定,this指向obj3
        fn1.call(obj3) // new=>this 100 显示绑定,this指向obj
    }
}
obj3.b()

参考: juejin.cn/post/738649…