Skip to content

Instantly share code, notes, and snippets.

@JonDum
Created September 17, 2011 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonDum/1224324 to your computer and use it in GitHub Desktop.
Save JonDum/1224324 to your computer and use it in GitHub Desktop.
Suggestion for how JS class syntax should be
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);
}
/**
* 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