Reputation: 39
Can someone explain me how they are creating a "method" method on an object.
var foo = {};
foo.method = function(name, cb){
this[name] = cb;
};
Upvotes: 1
Views: 46
Reputation: 44145
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();
Upvotes: 3