Skip to content

Instantly share code, notes, and snippets.

@martinklepsch
Last active April 7, 2017 10:12
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 martinklepsch/b50e52a5cb80b81d3a43d05334e3803c to your computer and use it in GitHub Desktop.
Save martinklepsch/b50e52a5cb80b81d3a43d05334e3803c to your computer and use it in GitHub Desktop.
Trying to compile some common JS patterns and their respective ways to extern them for Closure advanced compilation
// plain function
function add_one(x) {
  return 1 + x;
}

// constructor
MyClass = function(name) {
  this.myName = name;
};

// static method
MyClass.version = function() {
  return "1.2.3"
};

// instance method
MyClass.prototype.myMethod = function() {
  alert(this.myName);
};

This are the externs

var add_one;
var MyClass;
MyClass.version = function(){};
MyClass.prototype.myMethod = function(){};
// accessing myName directly will not work unless you use string keys my_class_instance["myName"]
// to allow accessing myName via property syntax you can add an extern similar to the one for myMethod:
// MyClass.prototype.myName = {}

Note that the externs here are "bare-minimum". They don't provide any typing information beyond "this is a function" or "this is data". To prevent renaming during advanced compilation that is enough. For the better optimization and compiler warnings this will not necessarily be sufficient. (That said I'm not sure how useful these are for externed libraries.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment