Quote:
- There are a great deal of custom functions which are not differentiated from callbacks used by the game. Our recommendation is that internal script functions have names beginning with
_
or $
.
I’d like to clarify this a bit.
Any property Oolite adds to an object, other than the global object and arrays, will have a name beginning with a lowercase letter. Therefore, if you add your own property to any object that Oolite has a direct interest in, it should not start with a lowercase letter. The symbols
_
and
$
are permitted characters at the start of an identifier which are very obviously not lowercase letters. (A convention I now use, but which isn’t used in the Oolite built-in scripts, is to use
$
for custom properties and
_
for variables used to hide state in closures, a pattern I’m not going to go into here.)
You could also start your property names with other characters and access them with
[]
syntax, like
this["& what a clever name!"] = 3;
. But that would be silly.
There are two other things that can appear in identifiers, digits and uppercase letters. An identifier can’t start with a digit, so that’s out. By convention, identifiers starting with uppercase letters are
constructors, functions whose purpose is to set up an object in conjunction with the
new
operator. The constructors you’re most likely to see in Oolite scripts are
Vector3D
and
Quaternion
, as in
let v = new Vector3D(1, 0, 0);
. These very roughly correspond to
classes in other object-oriented languages.
All of Oolite’s constructors are globals, and there’s no reason to expect that to change, so it’s OK for a script to have constructors as properties whose names don’t begin with a
_
or
$
. This isn’t very interesting for most scripts, but could be useful for libraries. For example, a library might export a constructor
Frob
like so:
Code:
this.name = "ahruman_frobLibrary";
this.Frob = function Frob(x)
{
// Set up this as a Frob object here.
Object.defineProperty(this, "x", { get: function () { return x; } });
}
Frob.prototype.plusOne = function plusOne()
{
return this.x + 1;
}
Which can be used like this:
Code:
this.startUp = function ()
{
let frobLib = worldScripts["ahruman_frobLibrary"];
let myFrob = new frobLib.Frob(3);
log("frobLib.test", myFrob.plusOne()); // Logs 4.
}