Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.