0

i have this working in it's current form listed below, but is there any way I could make the exported function in component_a.js below be an arrow function and still have it work?

the main part I'm confused about is how to use apply or bind with arrow functions (or if that is even possible).

goal: I wish to attach an arrow function to a map property of an object, and have that object call said function and apply its "this" to it.


component_a.js

export default function(args){  //<--- is this possible to be changed to an arrow function?
    this.x = Math.round(this.x)
    this.y = Math.round(this.y)
}

index.js

export {default as component_a} from './component_a.js'
export {default as component_a} from './component_b.js'

entity.js

import * as components from './index.js'

export default () => {
    return {
        components: new Map,
        add_component: function(component){
            //here is where i am trying to bind the component_a.js to "this" object (entity)
            this.components.set(component, components[component].bind(this)) 
        },
        update: function(dt) {
            this.components.forEach(component => {
                component(dt)
            })
        }
    }
}

usage.js

import entity from './entity.js'

const p = entity()
p.add_component('component_a')
export p
simon
  • 854
  • 1
  • 9
  • 23
  • 1
    You cannot change the function in component_a to an arrow function since `this` will no longer refer to the function but the scope that owns that function as far as I know – Sean Jun 02 '20 at 02:57
  • yes but what exactly owns the function in this case? the exporter or the map? – simon Jun 02 '20 at 03:09
  • the really weird part in chrome is when i tried with arrow function and tried to log "this" i would get undefined which is very unknown behavior for me. – simon Jun 02 '20 at 03:10
  • The top level `this` value in a module is `undefined`. Functions are not "owned" by anything. In an arrow function `this` is resolved lexically like any other variable. – Felix Kling Jun 02 '20 at 07:26

0 Answers0