Skip to content

Instantly share code, notes, and snippets.

@nilbus
Created September 5, 2011 15:00
Show Gist options
  • Save nilbus/1195177 to your computer and use it in GitHub Desktop.
Save nilbus/1195177 to your computer and use it in GitHub Desktop.
How do I create a new instance of a class from within a class method?
class TreeNode
constructor: (@tree, @id, @name, @data={}, @children=[]) ->
@set_color() unless @data.$color
@name = @id if !@name? or @name.blank()
@create_root: (tree) -> # acts as a TreeNode class method. Called like TreeNode.create_root(tree)
new this tree, 'root'
# "new this" is incorrect and does not work.
# I want to call the equivalent of "new VariationTreeNode(...)" or "new ProfileTreeNode(...)",
# based on the class I call create_root on - eg: ProfileTreeNode.create_root(tree)
class VariationTreeNode extends TreeNode
color: -> 'yellow'
class ProfileTreeNode extends TreeNode
color: -> '#F44'
// Compiled coffeescript
var ProfileTreeNode, TreeNode, VariationTreeNode;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
};
TreeNode = (function() {
function TreeNode(tree, id, name, data, children) {
this.tree = tree;
this.id = id;
this.name = name;
this.data = data != null ? data : {};
this.children = children != null ? children : [];
if (!this.data.$color) {
this.set_color();
}
if (!(this.name != null) || this.name.blank()) {
this.name = this.id;
}
}
TreeNode.create_root = function(tree) {
return new this(tree, 'root');
};
return TreeNode;
})();
VariationTreeNode = (function() {
__extends(VariationTreeNode, TreeNode);
function VariationTreeNode() {
VariationTreeNode.__super__.constructor.apply(this, arguments);
}
VariationTreeNode.prototype.color = function() {
return 'yellow';
};
return VariationTreeNode;
})();
ProfileTreeNode = (function() {
__extends(ProfileTreeNode, TreeNode);
function ProfileTreeNode() {
ProfileTreeNode.__super__.constructor.apply(this, arguments);
}
ProfileTreeNode.prototype.color = function() {
return '#F44';
};
return ProfileTreeNode;
})();
class TreeNode
constructor: ->
alert "constructed with color #{@color()}"
@create_root: ->
new this()
class VariationTreeNode extends TreeNode
color: -> 'yellow'
class ProfileTreeNode extends TreeNode
color: -> '#F44'
ProfileTreeNode.create_root()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment