Instantly share code, notes, and snippets.

Embed
What would you like to do?
Really simple example of abstracts - creating an "extension" of AnchorElement with a custom constructor. Uses all inline code, and shows how implicit casts can be used when interacting with API that expects the underlying type.
// Compile with `haxe -js AbstractExample.js -dce full -main AbstractExample.hx`
import js.html.AnchorElement;
class AbstractExample {
static function main() {
var myAnchor = new MyAnchor( "http://google.com", "Click here!" );
expectsAnchor( myAnchor ); // Notice how it automatically casts back down to AnchorElement
}
static function expectsAnchor( a:AnchorElement ) {
trace ( a.href );
}
}
abstract MyAnchor( AnchorElement ) from AnchorElement to AnchorElement {
public inline function new( href:String, text:String ) {
var doc = js.Browser.document;
this = doc.createAnchorElement();
this.href = href;
this.innerHTML = text;
}
}
(function () { "use strict";
var AbstractExample = function() { }
AbstractExample.main = function() {
var myAnchor;
var this1;
var doc = window.document;
this1 = doc.createElement("a");
this1.href = "http://google.com";
this1.innerHTML = "Click here!";
myAnchor = this1;
AbstractExample.expectsAnchor(myAnchor);
}
AbstractExample.expectsAnchor = function(a) {
console.log(a.href);
}
AbstractExample.main();
})();
@jasononeil

This comment has been minimized.

Owner

jasononeil commented Nov 7, 2013

The "this1" and "_this" references in the generated code are a little weird... not sure if there's a way to clean that up. But other than that you can see that it's all completely inline.

@jasononeil

This comment has been minimized.

Owner

jasononeil commented Nov 7, 2013

I updated the code to use var doc = js.Browser.document, which gets rid of the "_this" reference and makes the generated code a little easier to understand...

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