0
 let objFirst = {
    name: 'Bill',
    age: 55,
    getName: function () {
      console.log(this.name)
    },
    getAge: function () {
      console.log(this.age)
    }
 }
 function returnProp (obj) {
    //...code
 }
 let objSecond = returnProp (objFirst );
 objSecond.getName(); //Bill
 objSecond.getAge(); //55

I know it can be solved like this

 function returnProp (obj) {
    return obj
 }

I wanna do it with 'call', 'apply' or 'bind' methods, but can't figure out how, can someone explain ?
I tried something like this, but it doesn't work.

 function returnProp (obj) {
       obj.getName.bind(objFirst)
       obj.getAge.bind(objFirst)
 }
plex
  • 3
  • 2

2 Answers2

0

I am not sure if I understood you correctly, but I hope this helps:

This creates a new object which only contains the properties you want, which, when called call the method of the original object.

let objFirst = {
  name: 'Bill',
  age: 55,
  getName: function() {
    console.log(this.name)
  },
  getAge: function() {
    console.log(this.age)
  }
}

function returnProp(obj) {
  return {
    getName: obj.getName.bind(obj),
    getAge: obj.getAge.bind(obj)
  }
}
let objSecond = returnProp(objFirst);
objSecond.getName(); //Bill
objSecond.getAge(); //55
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38
0

As I understand, you want to clone the first object rather than reference it. You should look into lodash (_). Lodash has cloneDeep() method that allows you to clone the entire object.

obj2 = _.cloneDeep(obj1);
Sujil Maharjan
  • 1,307
  • 10
  • 12