Last active
August 29, 2015 14:23
-
-
Save joernroeder/849d92384cc4e1fdc3fb to your computer and use it in GitHub Desktop.
Javascript Factory example which returns different (Sub)Classes
This file contains hidden or 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
// class pattern helpers | |
// | |
// @see https://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript | |
// | |
Function.prototype.makeSubclass= function() { | |
function Class() { | |
if ('_init' in this) | |
this._init.apply(this, arguments); | |
} | |
Function.prototype.makeSubclass.nonconstructor.prototype= this.prototype; | |
Class.prototype= new Function.prototype.makeSubclass.nonconstructor(); | |
return Class; | |
}; | |
Function.prototype.makeSubclass.nonconstructor= function() {}; | |
// Foo base class | |
var Foo = Object.makeSubclass(); | |
// der constructor wird normalisiert und _init dient als neue constructor function | |
Foo.prototype._init = function (x, y, text) { | |
// default class options | |
this._foobar = 'barfoo'; | |
// parameter zur klasse hinzufügen | |
this._x = x; | |
this._y = y; | |
this._text = text; | |
}; | |
Foo.prototype.getX = function () { | |
return this._x; | |
}; | |
Foo.prototype.getY = function () { | |
return this._y; | |
}; | |
Foo.prototype.getText = function () { | |
return this._text; | |
}; | |
// Foo construction end | |
// Bar subclass | |
var Bar = Foo.makeSubclass(); | |
Bar.prototype.getX = function () { | |
return this._x + 50; | |
}; | |
/* | |
Constructor extension (ein extra parameter r) | |
Bar.prototype._init= function(x, y, text, r) { | |
Foo.prototype._init.call(this, x, y, text); // gleichzusetzen mit dem super call in java | |
// add extra parameter | |
this._r = r; | |
}; | |
*/ | |
// Bar subclass end | |
var Factory = { | |
// unterstrich am anfang, zeigt developern an, dass dies eine private property ist | |
_classes: { | |
default: Foo, | |
right: Bar | |
}, | |
// create function | |
create: function (x, y, text) { | |
var className = 'default'; | |
if (x > 150) { | |
className = 'right'; | |
} | |
return new this._classes[className](x, y, text); | |
} | |
}; | |
var myClass = Factory.create(100, 100, 'foobar'); // Factory gibt ein neues Foo zurück | |
var secondClass = Factory.create(200, 200, 'foobar'); // Factory gibt ein neues Bar zurück | |
console.log('myClass.getX() -->', myClass.getX()); | |
console.log('secondClass.getX() -->', secondClass.getX()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment