Created
November 18, 2013 19:04
-
-
Save AfonsoTsukamoto/7533422 to your computer and use it in GitHub Desktop.
Javascript classes. Just as reminder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Class Ex. | |
var JSClass = function(args){ | |
//This is only accessible through a getter | |
var _arg = args[0]; | |
// This is accesible by json notation: jsclassInstance.jsonAttr | |
this.jsonAttr = args[1]; | |
var func = function(args){ | |
// This function either is returned or is private to the class | |
alert('hey!'); | |
}; | |
return{ | |
// The json return | |
getterArg: function(arg){ | |
return _arg; | |
}, | |
// A getter/setter | |
arg: function(arg){ | |
if(arg == null) return _arg; | |
_arg = arg; | |
}, | |
accessInnerVarsWrong: function(){ | |
// This is totally fine! | |
_arg = this.arg(); | |
var json = this.jsonAttr; | |
// But this: | |
var i = 0; | |
$('.body').children().each(function(){ | |
// This, not fine. jQuery Scope | |
this.arg(i); | |
i++; | |
}); | |
}, | |
accessInnerVarsTurnArround: function(){ | |
// This is, again, totally fine! | |
_arg = this.arg(); | |
var json = this.jsonAttr; | |
// And this too: | |
var i = 0; | |
var self = this; | |
$('.body').children().each(function(){ | |
// This is now fine. jQuery Scope too but self has a reference to this, the object. | |
self.arg(i); | |
i++; | |
}); | |
} | |
}; | |
}; | |
// Usage | |
var anObject = new JSClass('lalala'); | |
anObject.arg(10); | |
var a = anObject.arg(); | |
var b = anObject.jsonAttr; | |
// Class methods ?! | |
// Evaluating a jscript function as an expression does the trick | |
var JSClassWM = (function(){ | |
this.x = 0; | |
this.y = 0; | |
return{ | |
x: function(arg){ | |
if(arg == null) return this.x; | |
this.x = arg; | |
}, | |
y: function(arg){ | |
if(arg == null) return this.y; | |
this.y = arg; | |
}, | |
getArea: function(){ | |
return this.x*this.y; | |
}, | |
getPer: function(){ | |
//Not coooolll man! | |
return this.x*2 + this.y*2; | |
}, | |
// This one can be used as a 'pure' class method | |
areaOf:function(x,y){ | |
return x*y; | |
} | |
} | |
})(); | |
// Usage | |
JSClassWM.x(10); | |
JSClassWM.y(10); | |
var a = JSClassWM.getArea(); | |
//=> a = 100 | |
var b = JSClassWM.areaOf(2,2); | |
//=> b = 4 | |
// Then, I like to use a 'main' like this: | |
$(document).ready(function(){ | |
// Stuff here! | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment