I have an object:
var Person = function(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log("Hello" + this.name + ", " + this.age);
}
var sam = new Person("Sam", 31);
I want to call Person.sayHello as onclick callback and I found out that I can do it with bind method.
$("#button").on("click", Person.sayHello.bind(sam));
Maybe there is more generic solution for it or some specific approach for jQuery to solve this problem at jQuery?
I need to add one note. I can have multiple instances of Person class and I want to make click to work for all of them. I thought about some loop over all Person instances and binding them to callback.
bind()is about the best way to do it. you could use an anon+closure, but usually bind() solutions are simpler and more re-usable.Personsand put them intobind