skip to Main Content

If one has an existing object obj:

const obj = {
  i: 0,
  foo(){ 
    console.log(this.i) 
    this.i +=1
  }
}

obj.foo() // => 0

Is it possible to merge a function into it:

// the following function code should be added to `obj`
function obj(){
  this.foo()
}

// after the merge the following should both work:
obj.foo() // => 1
obj() // => 2

3

Answers


  1. You can merge function to object using Object.assign. I changed obj() to baz() to make it more clear.

    const obj = {
      i: 0,
      foo() {
        console.log(this.i);
        this.i += 1;
      }
    };
    
    function baz() {
      this.foo();
    }
    
    Object.assign(obj, { baz });
    obj.foo() // => 0
    obj.baz() // => 1
    

    However when you call baz(), it will throw error because it doesn’t understand the context this in baz(). So you need to call baz() with obj as the context

    baz.call(obj); // => 2
    
    Login or Signup to reply.
  2. I am not sure how the obj function is merged into the obj object if you want to call it standalone. However, you could use a bound function instead.

    Besides: You cannot have a constant obj and a function obj that share the same name. I therefor changed the function name to fn:

    const obj = {
      i: 0,
      foo() {
        console.log(this.i);
        this.i += 1;
      }
    };
    
    function fn() {
      this.foo();
    }
    
    
    
    const bound = fn.bind(obj);
    
    
    
    bound();
    obj.foo();
    bound();
    Login or Signup to reply.
  3. there are multiple ways to add property to an object like :

    1.using dot notation, 
    2.using bracket [ ] notation, 
    3.using defineProperty(), 
    4.using spread operator, 
    5.using Object.assign() 
    
    
    const obj = {
      i: 0,
      foo(){ 
        console.log(this.i) 
        this.i +=1
      }
    }
    
    const newObj = {...obj, obj(){console.log("ok")}}
    newObj.obj()
    
    obj['bar'] = function(){
        console.log("bar")
    }
    
    obj.bar()
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search