How to directly invoke a function in a compound object (compositing vs inheritance)

Hi,

It’s kind of lame to say this, but I just discovered compositing rather than using prototyping. Here’s a quick example :

import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.117.1/build/three.module.js'

const can_fight = (state) => ({
	fight: () => {
		console.log(`${state.name} slashes at the foe!`);
		state.stamina--;
	}
})

export const mage = (name) => {
	let state = {
		name,
		health: 100,
		mana: 100,
		geo: new THREE.BoxGeometry(5, 1, 500),
		mat: new THREE.MeshPhongMaterial({
			color: "#000",
			specular: "#444",
			emissive: "#444",
			shininess: 0,
		}),
		scene: scene,
	}
	state.mesh = new THREE.Mesh(state.geo, state.mat);
	state.scene.add(state.mesh)
	return Object.assign(
		state,
		can_fight(state),
	);
}

let player = mage("mage")
player.fight()

What I would like to do is to have the possibility to directly invoke the ability “fight” in the creation of the object. Obviously if I do this, it doesn’t work. Is there a way to do this?

import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.117.1/build/three.module.js'

const can_fight = (state) => ({
	fight: () => {
		console.log(`${state.name} slashes at the foe!`);
		state.stamina--;
	}
})

export const mage = (name) => {
	let state = {
		name,
		health: 100,
		mana: 100,
		geo: new THREE.BoxGeometry(5, 1, 500),
		mat: new THREE.MeshPhongMaterial({
			color: "#000",
			specular: "#444",
			emissive: "#444",
			shininess: 0,
		}),
		scene: scene,
	}
	state.mesh = new THREE.Mesh(state.geo, state.mat);
	state.scene.add(state.mesh)
	return Object.assign(
		state,
		can_fight(state),
	);
//////////////////////////////////////////////////////////////////////////////
        // HERE WHAT I WOULD LIKE TO DO DIRECTLY IN MY OBJECT
        state.fight()
//////////////////////////////////////////////////////////////////////////////
}

let player = mage("mage")
//////////////////////////////////////////////////////////////////////////////
TO AVOID THIS :
// player.fight()
//////////////////////////////////////////////////////////////////////////////

  1. General note - if a coding structure / pattern / something makes you suddenly feel super smart - consider avoiding it like fire. It will not feel that way in a month when you’ll try to understand or modify it :see_no_evil: Code duplication looks worse but is quite trivial to handle compared to code magic.
  2. As for the code structure - spend a week playing with react (pre-hooks may be best), angular (2+), or vue. You don’t have to use any of them in the end - but these frameworks enforce code structures that will show you how to organise your own code in any framework / environment (ie. generalised classes / components, local / global states, two- and one-way data binding etc.) Three as a library, not a framework, can’t help much with teaching code structure fundamentals - it just draws stuff :pencil2:
1 Like