Skip to content

Instantly share code, notes, and snippets.

@jacegu
Created October 29, 2011 17:42
Show Gist options
  • Save jacegu/1324844 to your computer and use it in GitHub Desktop.
Save jacegu/1324844 to your computer and use it in GitHub Desktop.
Some weird stuff with contexts for a CoffeScript&Javascript beginner
set_name = (name) -> @name = name
set_name 'Juan'
console.log name #Juan
console.log @name #undefined
#How context works here is pretty weird...
#Looks like set_name is not evaluated on "this" context
#This seems quite true if we do:
set_name.call this, 'Juan' console.log @name #Juan
#If we looking at the compiled Javascript:
var set_name;
set_name = function(name) {
return this.name = name;
};
set_name('Juan');
console.log(name);
console.log(this.name);
#I'd say that functions have no context by default. Am I right?
#Or, maybe, the function itself is an object and has it's own context
#Need some clarification on this one
@eamodeorubio
Copy link

The execution context of a function (the 'this' keyword) depends only on the way you call/execute the function.
There are several ways of executing a function:
a) set_name('Juan') -> the context is the global object. What the global object is depends on the enviroment you are running. In a browser it is window, in node.js is an object called global.... You shouldn't use 'this' if you plan calling the function like this
b) set_name.call(someObject, 'Juan') -> This way 'this' is 'someObject'
c) set_name.apply(someObject, ['Juan']) -> This way 'this' is 'someObject'
d) someObject.set_name('Juan') -> This way 'this' is 'someObject'. But you need 'someObject' to have the function set_name. To do so you can just do someObject.set_name = set_name You can define too the method set_name using the constructor or its prototype

@jacegu
Copy link
Author

jacegu commented Oct 31, 2011

Thanks for your help @eamoderubio! It's crystal clear now :·)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment