Created
September 17, 2011 20:21
-
-
Save JonDum/1224324 to your computer and use it in GitHub Desktop.
Suggestion for how JS class syntax should be
This file contains hidden or 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 Point { | |
public x, y; | |
Point(x, y) | |
{ | |
this.x = x; | |
this.y = y; | |
} | |
public equals(point) { return x === point.x && y === point.y); | |
public length( return Math.sqrt(x * x + y * y); | |
} |
This file contains hidden or 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 Doc | |
*/ | |
class Point { | |
//---------------------------------- | |
// Private Members | |
//---------------------------------- | |
private var _x; | |
private var _y; | |
//---------------------------------- | |
// Constructor | |
//---------------------------------- | |
/** | |
* Constructor Doc | |
*/ | |
Point(x, y) | |
{ | |
//since function variables have the same name as class members | |
// use 'this' to refer to class variables | |
this._x = x; | |
this._y = y; | |
} | |
//---------------------------------- | |
// Methods | |
//---------------------------------- | |
private function myPrivateMethod() | |
{ | |
//private method | |
} | |
public function toString() | |
{ | |
return "["+x+", "+y+"]"; | |
} | |
public function get x() | |
{ | |
return _x; //Scope includes class variables | |
} | |
// Having the ability to define a setter for a private member | |
// helps reduce errors by checking the value before setting | |
// (as opposed to just having `public var x`). | |
// Setters and getters are not necessary, however; | |
// public var x, y; | |
public function set x(value) | |
{ | |
if(!value) | |
throw "Set y error"; //or whatever you want to do with it. | |
_x = value; | |
} | |
public function get y() | |
{ | |
return _y; | |
} | |
public function set y(value) | |
{ | |
if(!value) | |
throw "Set y error"; | |
return _y; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment