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



可以在不使原型复杂化的情况下编写它吗?

为什么?当前的代码可以满足我的需求,但是它困扰着我,它是多么的琐碎以及它是多么容易出错,而且由于内容重复,似乎也在浪费性能。

目的?我花在原型上的时间越多,如果不是这种情况,我就会感觉到代码会更简单、更切中要害。

特别是如果可以重写系统蓝图中的this函数以将实例作为参数。如果对象函数 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()

部分答案,根据@Bellian的评论建议实现,肯定有点在路上,谢谢!

哪里?内部函数系统构建器(...(:

而不是

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)}

最新更新