Skip to content

Instantly share code, notes, and snippets.

@ideadapt
Last active December 18, 2015 21:09
Show Gist options
  • Save ideadapt/5845347 to your computer and use it in GitHub Desktop.
Save ideadapt/5845347 to your computer and use it in GitHub Desktop.
coffeescript class, instance (variables/methods) and this context issues.
class Animal
@classVar = 'class var'
constructor: (@options) ->
@memberVar = 'the member'
_privateMethod: (param) ->
console.log('private instance method ' + param)
instanceMethod: ->
@_privateMethod(@options)
@classMethod: ->
console.log('class method, accessing ' + @classVar)
a = new Animal(opt1: 'aha')
a.instanceMethod()
Animal.classMethod()
# a.classMethod() not possible in coffeescript
console.log(Animal.classVar)
console.log(a.memberVar)
a2 = new Animal()
Animal.classVar = 'classVar2'
Animal.classMethod()
a2.memberVar = 'memberVar2'
console.log(a2.memberVar)
console.log(a.memberVar)
## COMPILED JAVASCRIPT
var Animal, a, a2;
Animal = (function() {
Animal.name = 'Animal';
Animal.classVar = 'class var';
function Animal(options) {
this.options = options;
this.memberVar = 'the member';
}
Animal.prototype._privateMethod = function(param) {
return console.log('private instance method ' + param);
};
Animal.prototype.instanceMethod = function() {
return this._privateMethod(this.options);
};
Animal.classMethod = function() {
return console.log('class method, accessing ' + this.classVar);
};
return Animal;
})();
a = new Animal({
opt1: 'aha'
});
a.instanceMethod();
Animal.classMethod();
console.log(Animal.classVar);
console.log(a.memberVar);
a2 = new Animal();
Animal.classVar = 'classVar2';
Animal.classMethod();
a2.memberVar = 'memberVar2';
console.log(a2.memberVar);
console.log(a.memberVar);
## CONSOLE OUTPUT
private instance method [object Object]
class method, accessing class var
class var
the member
class method, accessing classVar2
memberVar2
the member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment