1

Can someone explain me how they are creating a "method" method on an object.

var foo = {};

foo.method = function(name, cb){
  this[name] = cb;
};

1 Answer 1

3

They're assigning the key method to a function - that's a method. If you're wondering how the key method is used, it's because it's not a reserved keyword in JavaScript.

The actual method creates a new method with the provided name, and sets it to the cb. (This can also be used to make properties, not just methods).

var foo = {};

foo.method = function(name, cb) {
  this[name] = cb;
};

foo.method("sayHello", () => console.log("Hello!"));
foo.sayHello();

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.