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;
};
Jack Bashford
44.3k11 gold badges56 silver badges84 bronze badges
asked Jun 1, 2019 at 2:30

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();

answered Jun 1, 2019 at 2:37
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.