【问题标题】:concatenative inheritance two methods with same signature串联继承具有相同签名的两个方法
【发布时间】:2021-11-12 20:36:07
【问题描述】:

下面的代码只打印事件内容,如何使打印的 WheatherData.value 数字?我来自java,我习惯这样做。

const Event = (time, place) => {
    var _time = time
    var _place = place

    return {
        getTime() {
            return _time
        },
        getPlace() {
            return _place
        },
        updateTime() {
            _time = new Date(Date.now())
        },
        toString() {
            return 'Time: ' + _time + '\nPlace: ' + _place
        }
    }
}

const WeatherData = (value, time, place) => {
    var _event = Event(time, place)
    var _value = value
    const getValue = () => { return _value }
    const toString = () => { return '\nValue: ' + _value + _event.toString() }
    return Object.assign({ getValue, toString }, _event)
}



const wd = WeatherData(10.1, new Date(Date.now()), 'Chisinau, Moldova')

console.log(wd.toString())

//Time: Sat Sep 18 2021 08:49:10 GMT+0200 (Central European Summer Time)
//Place: Chisinau, Moldova
// no value printed

【问题讨论】:

  • OP 想要在WeatherData 级别混合自己的Event 方法的原因是什么?为什么不通过纯聚合保持模型(ing)清洁,从而使Event 类型成为WeatherData 类型的成员?所谓的“串联继承”也没有单一的继承特性,而是通过闭包生成工厂函数进行对象扩充。因此,为了通过本地范围保护数据值,每个对象都必须实现自己的 getter 和 setter 功能,这些功能可以访问和更改此类本地数据。

标签: javascript object inheritance javascript-objects


【解决方案1】:

return Object.assign({}, _event, { getValue, setValue, toString })

这对我有用,这是正确的方法吗?我用这种方式覆盖了eventtoString方法

【讨论】:

    【解决方案2】:
    return Object.assign({ getValue, toString }, _event)
    

    上面的行导致了问题。当您将_event 对象分配给{ getValue, toString } 对象时,您只是覆盖了WeatherData 函数的toString 方法。相反,只需从您的 WeatherData 函数中返回 { getValue, toString },如下所示;

    const WeatherData = (value, time, place) => {
        var _event = Event(time, place);
        var _value = value
    
        const getValue = () => { return _value }
        const toString = () => { return '\nValue: ' + _value + '\n' + _event.toString() }
    
        return { getValue, toString }
    }
    

    【讨论】:

    • 但是,WeatherData 对象不会继承 Event 的属性
    • 它打破了串联继承
    猜你喜欢
    • 2011-02-19
    • 1970-01-01
    • 2011-01-23
    • 2015-03-20
    • 1970-01-01
    • 2018-11-04
    • 2011-05-29
    • 2014-08-29
    相关资源
    最近更新 更多