javascript - Javascript中Class内部对象,成员函数需要多个this指向如何解决?

 

问题描述:

题目描述

在构造Class时,有一些属性对象结构比较复杂,其中的成员函数逻辑不仅需要访问对象中的其他成员变量,还需要访问类中的属性/方法,比如下面一段代码:

class Dog {
    name = '二哈'
    action = {
        bark:function(){
            console.log(this.name, '汪汪')
        }
    }
}
dog.action.bark() //undefined 汪汪

Dog类中有一个aciton属性,其中的bark方法需要获取类的name属性,上面的代码无法直接获取到,输出结果是//undefined '汪汪'

可以通过bind()方法手动改变this指向:

class Dog {
    name = '二哈'
    action = {
        bark:function(){
            console.log(this.name, '汪汪')
        }.bind(this)
    }
}
dog.action.bark() //二哈 汪汪

但如果bark方法内部同时需要访问action对象的其他成员属性值时,无法通过上面的方法进行解决,例如:

class Dog {
    name = '二哈'
    action = {
        ishappy: true,
        bark:function(){
            if(this.ishappy)
                console.log(this.name, '汪汪')
            else
                console.log(this.name, '呜呜')
        }.bind(this)
    }
}
const dog = new Dog()
dog.action.bark() // 二哈 呜呜

怎么修改能够使其输出期望的二哈 汪汪呢?


 

第 1 个答案:

class Dog {
    name = '二哈'
    action = {
        ishappy: true,
        bark: () => {
            if(this.action.ishappy)
                console.log(this.name, '汪汪')
            else
                console.log(this.name, '呜呜')
        }
    }
}
const dog = new Dog()
dog.action.bark() // 二哈 汪汪
dog.action.ishappy = false
dog.action.bark() // 二哈 呜呜

node v18.13.0npm 9.3.1使用vite创建的react工程,package文件内容如下,改用antd4再引入一下antd/dist/antd.css就正常显示v5版 ...