Skip to content

Instantly share code, notes, and snippets.

@antoniojps
Created April 9, 2017 15:01
Show Gist options
  • Save antoniojps/37f0f6b8ab3d25028f95fe606fd0b20a to your computer and use it in GitHub Desktop.
Save antoniojps/37f0f6b8ab3d25028f95fe606fd0b20a to your computer and use it in GitHub Desktop.
Javascript: Call, Apply e Bind
var obj = {
name: 'John Doe',
greet () {
console.log(`Hey ${this.name}`);
}
};
obj.greet(); // Hey John Doe
// Chamar o metodo e mudamos o this, diferença entre call e apply é que no apply os params sao uma array
obj.greet.call({name:'Manel Alberto'},param1,param2,param3); // Hey Manel Alberto
obj.greet.apply({name:'Manelito Alberto'},[param1,param2,param3]); // Hey Manelito Alberto
// Bind muda a this mas nao invoca
function MyObject(element) {
this.elm = element;
element.addEventListener('click', this.onClick.bind(this), false);
};
MyObject.prototype.onClick = function(e) {
var t=this; //do something with [t]...
//without bind the context of this function wouldn't be a MyObject
//instance as you would normally expect.
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment