我真的需要在javascript中使用protoypes吗? (实例)

时间:2017-08-01 22:08:56

标签: javascript

这可以写成没有复制原型的东西吗?

为什么?当前的代码可以实现我想要的功能,但它让我感到烦恼,它是如何遵循它以及它容易出错的原因,也似乎是性能浪费,因为事情是重复的。

目标?我花在使用原型上的时间越多,我觉得代码会更简单,如果情况不是这样的话就会更加明确。

  

特别是如果可以重写SystemBlueprint中的this-functions而不是将实例作为参数。如果对象函数Log()和Out可能只是普通的对象?如何在SystemBuilder之外提取Log或Out?

Jsbin中的完整代码

  

https://jsbin.com/pigosijaxo/edit?js,console(已更新)

// Local for each System object
var SystemData = {
    name: '?',
    id: 1,
    actions: [],
    destinations: []
}

// Variables shared among all Systems
const SystemShare = {
    global: 1
}

// this-Functions shared among all Systems
function SystemBlueprint() {}
SystemBlueprint.prototype = {
    run() {
        var length = this.actions.length
        for (var i = 0; i < length; i++) {
            var result = this.actions[i](arguments, this)
            if (result && this.destinations.length > 0) {
                for (var n = 0; n < this.destinations.length; n++) {
                    this.destinations[n].call(null, result)
                }
            }
        }
    },
    does(algorithm) {
        this.actions.push(algorithm)
        return this
    },
    random(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
}

function SystemBuilder(name) {
    // copy shared methods
    var system = Object.create(SystemBlueprint.prototype)
    Object.assign(system, JSON.parse(JSON.stringify(SystemData))) //deep copy

    system.name = name
    system.id = SystemShare.global++

    function Log() {}
    Log.prototype.local = () => console.log('fields: ' + JSON.stringify(Object.keys(system))),
    system.log = new Log()

    function Out(){}
    Out.prototype.into = (destination) => {
        system.destinations.push(destination)
        return system
    }
    system.out = new Out()

    system.trigger = {}
    function OnEvent(trigger){
        if(trigger === undefined) return
        trigger.call(null, system.run.bind(system))
        return system
    }
    system.trigger.on = new OnEvent()
    return system
}

var system = new SystemBuilder()
system.my = 'Testing'
system.log.local()
system.does( () => 'printing output...')
system.out.into(console.log)
system.run()

1 个答案:

答案 0 :(得分:0)

部分答案,由@Bellian的评论建议实施,有点肯定,谢谢!

哪里?内部功能SystemBuilder(...):

而不是

function Log() {}
Log.prototype.local = () => console.log('fields: ' + JSON.stringify(Object.keys(system))),
system.log = new Log() 

这样做

function _local(system){
  console.log('fields: ' + JSON.stringify(Object.keys(system)))
}
system.log = {local: _local.bind(this, system)}