gpt4 book ai didi

javascript - 我真的需要在 javascript 中使用原型(prototype)吗? (实际例子)

转载 作者:行者123 更新时间:2023-11-28 04:20:54 24 4
gpt4 key购买 nike

可以在不使用原型(prototype)来复杂化事物的情况下编写此代码吗?

为什么? 当前的代码做了我想要的事情,但它让我困扰,它是多么复杂,它是多么容易出错,而且似乎也浪费了性能,因为事情是重复的。

目标?我使用原型(prototype)的时间越多,我就越感觉如果不是这样的话,代码会更简单、更切题。

Especially if the this-functions in SystemBlueprint can be rewritten to take an instance as argument instead. And if object Function Log() and Out could just be plain objects somehow? How can Log or Out be extracted outside of SystemBuilder?

Jsbin 中的完整代码

https://jsbin.com/pigosijaxo/edit?js,console (Updated)

// 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 评论建议的实现,肯定有一点进展,谢谢!

哪里?内部函数 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)}

关于javascript - 我真的需要在 javascript 中使用原型(prototype)吗? (实际例子),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45448439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com