2

i have this class

import { ObjectUtilities } from '~/utils/';

class Object{
    constructor(object) {

        Object.assign(this, { ...object });

    }

    utils = ObjectUtilities;
}

and this class with the statis method also (class contains many static methods)

class ObjectUtilities {

  static getKey(object){
    return object.key;
  }
}

and i want to know if its possible to share the "this" from the Object class to the static method "getKey(object)"

want to do it as:

let x = new Object(object);
x.utils.getkey(this);

(ObjectUtilities as many static funcs i dont want to do it for each of them)

thanks for helping me out...

Goor Lavi
  • 412
  • 3
  • 16
  • 1
    What you describe is not a static method any more. You want to use `ObjectUtilities.getKey(x)` instead. – Bergi Aug 20 '17 at 09:49
  • 1
    `utils = ObjectUtilities;` and `{ ...object }` are not valid ES6. And you shouldn't do either anyway. – Bergi Aug 20 '17 at 09:50
  • 1
    [Don't ever use a `class` of only static methods](https://stackoverflow.com/q/29893591/1048572) – Bergi Aug 20 '17 at 09:57
  • It's unclear why ObjectUtilities is there. If it's supposed to contain common methods for some classes, use inheritance and skip `static`. – Estus Flask Aug 20 '17 at 12:05

1 Answers1

2

You can add a constructor to the ObjectUtilities class where you bind the given context to the getKey function:

class ObjectUtilities {
  constructor(_this) {
    this.getKey = this.getKey.bind(_this);
  }
 
  getKey() {
    return this.key;
  }
}

class MyObject {
    constructor(object) {
        Object.assign(this, { ...object });
        this.utils = new ObjectUtilities(this);
    }
}

const objectFoo = { key: 'foo' };
const objectBar = { key: 'bar' };

let x = new MyObject(objectFoo);
let y = new MyObject(objectBar);

console.log(x.utils.getKey(), y.utils.getKey());
Erazihel
  • 7,295
  • 6
  • 30
  • 53
  • for this solution i need to send "x" object again i wanted to know if i can do something like x.utils.getKey(); and do the this binding inside the class – Goor Lavi Aug 20 '17 at 09:51
  • @GoorLavi I've updated my answer, check if it's okay for you :) don't forget to upvote and validate if it is! – Erazihel Aug 20 '17 at 10:04
  • Please put the `this.utils = new ObjectUtilities(this);` inside the constructor as is proper in ES6. – Bergi Aug 20 '17 at 11:22