0

I am just playing around with bind. And wanted to understand the below code -

let admin = {
    name: "admin",
    id: 1,
    create() {
      return `${this.name} can create`;
    },
    edit() {
      return `${this.name} can edit`;
    },
    delete() {
      return `${this.name} can delete`;
    },
    read() {
      return `${this.name} can read`;
    }
  };
  
  let editor = {
    name: "editor",
    id: 2,
    edit: admin.edit.bind(this)
  };
  
  const editorEdit = admin.edit.bind(editor);

  console.log(editor.edit()); // undefined can edit
  console.log(editorEdit()); // editor can edit 

Wanted to know what is the difference between the two console statement.

Som
  • 144
  • 2
  • 9

1 Answers1

3
  let editor = {
    name: "editor",
    id: 2,
    edit: admin.edit.bind(this)
  };

this isn't the object being constructed, but rather the this of the running context. Most likely the global object in this case. That's why it looks for window.editor (which is undefined).

let variable declarations don't get mixed up with the global object and you can't really reference the object until outside the literal (it just doesn't exist).

You can do:

let editor = {
   name: "editor",
   id: 2
};

editor.edit = admin.edit.bind(editor);

That being said, you could choose to not bind it.

let editor = {
    name: "editor",
    id: 2,
    edit: admin.edit
};

Should also work.

let admin = {
    name: "admin",
    id: 1,
    create() {
      return `${this.name} can create`;
    },
    edit() {
      return `${this.name} can edit`;
    },
    delete() {
      return `${this.name} can delete`;
    },
    read() {
      return `${this.name} can read`;
    }
  };
  
  let editor = {
    name: "editor",
    id: 2,
    edit: admin.edit
  };
  
  let otherEditor = {
    name: "OtherEditor",
    id: 2
  }
  otherEditor.edit = admin.edit.bind(otherEditor);

  const editorEdit = admin.edit.bind(editor);

  console.log(editor.edit()); // editor can edit
  console.log(otherEditor.edit()); // OtherEditor can edit
  console.log(editorEdit()); // editor can edit 
MinusFour
  • 13,913
  • 3
  • 30
  • 39
  • can we fix this? – Som Jun 14 '21 at 17:17
  • 2
    Not inside the object literal, that I can think of. The object isn't constructed until after the literal gets parsed, so you can't reference it. – MinusFour Jun 14 '21 at 17:19
  • we can change otherEditor.edit = admin.edit.bind(otherEditor); to otherEditor.edit = admin.edit; still will get the same ans. – Som Jun 14 '21 at 18:02
  • Yes, they would both work. It all really depends on whether you actually need that function to be bound. – MinusFour Jun 14 '21 at 18:05