GNOME Javascript Introduction

Welcome to GNOME Javascript (GJS)! This first page details key differences from other Javascript frameworks you've used in the past.

Imports & Modules

In GJS every file is treated as a "module" and any variable declared as using 'var' (or global scope) is exported. Each "module" is imported using the 'imports' object using the pattern imports.[fileName] where the file's literal name is fileName.js. If your fileName contains a character that is not a valid Javascript identifier you can access it using the object+key syntax: object['fileName'].

a.js:

var A = class A { }

b.js:

Standard SyntaxQuick Object Syntax
const A = imports.a;
let a = new A.A();
const { A } = imports.a;
let a = new A();

Import Versioning

In A GTK+ Application

Use pkg.require({}) !!

Elsewhere

Use imports.gi.Versions.Gtk = X; !!

Logging

console is not defined in GJS, for basic logging use the built-in function log(message)

Extending GObject Classes

GJS supports native ES6 classes but requires a few changes to any class that extends from a GObject class (a subclass of a GTK+ widget or of a GLib class for instance).

Standard ES6 ClassGObject Subclass
var A = class A {
    constructor(a, b){
        super(a);
        this.b=b;
    }
}
var A = GObject.registerClass(
    {
        GTypeName: 'A'
    },
    class A extends GObject.Object {
        _init(a, b) {
            super._init(a);
            this.b = b;            
        }
    }
);