Home > Software engineering >  Call a member function of a class inside JSON object in a shorter way
Call a member function of a class inside JSON object in a shorter way

Time:09-05

My code is as follows,

class myClass
{
    constructor()
    {
        this.memberVar1="";
        this.memberVar2="";
    }

    memberFunction1()
    {
        // memberFunction1 code
    }
}

var myObj = {
    objVar1 : someJsonObject,
    objVar2 : new myClass()
}

Instead of calling the memberFunction and memberVar1,memberVar2 like

myObj.objVar2.memberVar1;
myObj.objVar2.memberFunction1();

I wish to call them as follows

myObj.memberVar1;
myObj.memberFunction1();

Is there any way i can restructure myObj to achieve this ?

Thanks in advance

CodePudding user response:

This is one way of doing it:

const someObj = new myClass();

var myObj = {
    objVar1 : {},
    memberFunction1 : someObj.memberFunction1
}

Then call it like you want:

myObj.memberFunction1()

EDIT:

If you want to merge N number of members you can use Object.create like this:

const instance = new myClass();
const myObj = Object.create(instance);
myObj.memberFunction1()

CodePudding user response:

Functions are first class objects in Javascript, and a member of a Javascript class is just an object, so there's nothing stopping you setting the reference that myObj.memberFunction1 to whatever you like, including someJsonObject.memberFunction1, however you need to be aware that the behavior of this will be different depending on how you set the reference. This may be important to make your memberFunction behave correctly depending on context.

class myClass
{
    constructor()
    {
        this.memberVar1="";
        this.memberVar2="";
    }

    memberFunction1()
    {
        // memberFunction1 code
    }
}

let someJsonObject = {
    memberFunction1: function(source) {
        if (this === myObj) { console.log(`${source}: "this" is myObj`) }
        else if (this === someJsonObject) { console.log(`${source}: "this" is someJsonObject`) }
        else { console.log('JavaScript interpreter is insane') }
    }
}

var myObj = {
    objVar1 : someJsonObject,
    objVar2 : new myClass(),
    memberFunction1: someJsonObject.memberFunction1 // the assignment will cause "this" to point to myObj

}


myObj.memberFunction1('myObj')
someJsonObject.memberFunction1('someJsonObject')
myObj.objVar1.memberFunction1('myObj.objVar1') // myObj.objVar1 is === someJsonObject
myObj.memberFunction1 = myObj.memberFunction1.bind(someJsonObject) // using bind will make "this" point to whatever you like (i.e someJsonObject)
myObj.memberFunction1('myObj')
someJsonObject.memberFunction1('someJsonObject')
myObj.objVar1.memberFunction1('myObj.objVar1')

  • Related