0

How do I make foo() work?

file1.js:

module.exports = class Example{

    constructor(something){
        
        this.something = something
    }

    functions ={

        foo(){

            return this.something
        }
    }
}

file2.js:

const Example = require('./file1.js')
const object = new Example("among")

console.log(object.foo())
0

2 Answers 2

1

First: you have to access those functions via .functions since that's where they live

Second, this will not be correct, so you can either

  • Make foo an arrow function

  • or you can .bind(this) to a function - like with bar in this code

  • you can't use .bind when using function property shorthand though - i.e. foo() { return this.something }.bind(this) - but you can bind it in the constructor

See the code for all three solutions - and why you need to bind the non arrow functions

class Example{
    constructor(something){
        this.something = something;
        // bat needs to be bound here
        this.functions.bat = this.functions.bat.bind(this);
    }
    functions ={
        // "this" will be correct here
        foo: () => this.something,
        // bar needs to be bound to "this"
        bar: function() { return this.something }.bind(this),
        // you can't bind a shorthand property function though
        bat() { return this.something },
        // this is what happens with no bind
        baz() { return this.something },
    }
    
}

const object = new Example("among")

console.log('foo', object.functions.foo())
console.log('bar', object.functions.bar())
console.log('bat', object.functions.bat())
console.log('baz', object.functions.baz())

Sign up to request clarification or add additional context in comments.

1 Comment

i will set this as the answer when ill be able to
1

Remove functions:

class Example{

    constructor(something){
        this.something = something;
    }

    foo(){

        return this.something
    }
}

const object = new Example("among")

console.log(object.foo())

2 Comments

is there no other way? i wanted to group similiar functions like lets say logging functions in log
yea i just saw and deleted the previous comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.