Last active
December 27, 2015 15:48
-
-
Save jasononeil/7349949 to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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(); | |
})(); |
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
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.