Skip to content

Instantly share code, notes, and snippets.

@astannard
Created February 18, 2016 08:17
Show Gist options
  • Save astannard/5e786f024360c7d9f1f7 to your computer and use it in GitHub Desktop.
Save astannard/5e786f024360c7d9f1f7 to your computer and use it in GitHub Desktop.
Javascript this
this varies depending on the execution context and can sometimes lead to unexpected behaviour
ways of tackling this are:
newname = functionname.bind(object); // calling the bind method which exists on all JS functions creates a copy of the function
// with this scoped to the value of the object passed into the bind method.
newname(arg1,arg2); // newname will then need to be executed
functionname.call(object, arg1,arg2); // call executes the function but the first parameter is the object that you want to use for the this scop
functionname.apply(object, [arg1,arg2]); // its the same as call be it contains an array of arguments instead;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment