Hello I have a problem with how to do inheritance while declaring object prototypes with object literal syntax.
I have made two Fiddles to help you help me.
Fiddle1, This one works
Fiddle2, This one doesn't work
This is my base class, almost all objects is defined in this way in my application:
Base = function(param){
this.init(param);
}
Base.prototype = {
init: function(param){
this.param = param;
},
calc: function(){
var result = this.param * 10;
document.write("Result from calc in Base: " + result + "<br/>");
},
calcB: function(){
var result = this.param * 20;
document.write("Result from calcB in Base: " + result+ "<br/>");
}
}
This is how I succeed extending and overriding methods in Base:
Extend = function(param){
this.init(param);
}
Extend.prototype = new Base();
Extend.prototype.calc = function(){
var result = this.param * 50;
document.write("Result from calc in Extend: " + result+ "<br/>");
}
But I wanted to use the same style as the rest of the application so I started playing around with object literals but it is driving me nuts eagerly cheered on by eclipse and firebug with its nonsense response to my syntax.
Now on to the question of how do I convert my succeeded extension code to object literal style?
Here is one of many attempts (it don't compile but will give you an rough idea how I want the code to look like.)
Extend = function(param){
this.init(param);
}
Extend.prototype = {
: new Base(),
calc: function(){
var result = this.param * 50;
document.write("Result from calc in Extend: " + result+ "<br/>");
}
}
You want Object.make. Live Example
Extend = function(param){
this.init(param);
}
Extend.prototype = Object.make(Base.prototype, {
constructor: Extend,
calc: function(){
var result = this.param * 50;
document.write("Result from calc in Extend: " + result+ "<br/>");
}
});
If you want an ES5 compliant implementation of Object.make to just plug into your code then use
Object.make = function make (proto) {
var o = Object.create(proto);
var args = [].slice.call(arguments, 1);
args.forEach(function (obj) {
Object.getOwnPropertyNames(obj).forEach(function (key) {
o[key] = obj[key];
});
});
return o;
}
You need to extend the original prototype rather than assigning a new object as the prototype.
function extend(original, extension) {
for (var key in extension) {
if (extension.hasOwnProperty(key)) {
original[key] = extension[key];
}
}
};
var A = function () {};
var B = function () {};
B.prototype = new A();
extend(B.prototype, {
methodName: function () {}
});
Related
var createworker = function() {
var workcount;
var input;
(function() {
workcount = 0;
console.log("hello");
}());
var task1 = function() {
workcount += 1;
console.log("task1" + workcount);
};
var task2 = function(a) {
workcount += 1;
input = a;
console.log("task2" + workcount + "variable" + a);
};
var task3 = function() {
console.log(input);
};
return {
job1: task1,
job2: task2,
job3: task3
};
}
var worker = new createworker();
worker.job1();
worker.job2(2);
worker.job3();
var worker1 = createworker();
worker1.job1();
worker1.job2(2);
worker1.job3();
Both work same. Then why to use new and when to use it?
Both work same.
They reason they both work the same is that you're returning an object from createworker. That overrides the work that new did.
new is used with constructor functions. It does this:
Creates a new object backed by the object the constructor function's prototype property points ot
Calls the constructor function with this referring to that new object
In the normal case, the result of new functionname is a reference to the object that new created. But, if the constructor function returns a non-null object reference, the result of the new expression is that object instead. It's that "but" that's happening in your createworker example.
So your version of createworker doesn't need new, because of the way it's written.
And doing it that way is absolutely fine; in fact, there are people who always do it that way. If you wanted to use new with createworker, here's a version designed to be used that way (renamed CreateWorker, because by convention constructor functions are capitalized):
var CreateWorker = function() {
var workcount;
var input;
(function() { // Side note: This function is pointless. Just move
workcount = 0; // <− this line
console.log("hello"); // <− and this one
}()); // ...out into the body of `createworker`/`CreateWorker`
// Note we assign to properties on `this`
this.job1 = function() {
workcount += 1;
console.log("task1" + workcount);
};
this.job2 = function(a) {
workcount += 1;
input = a;
console.log("task2" + workcount + "variable" + a);
};
this.job3 = function() {
console.log(input);
};
// Note we aren't returning anything
};
I want to validate that the approach I'm using is correct when it comes to extend a prototype - supposing "extend" is the right word.
This topic gets a lot of clones. I'm still trying to properly understand this topic...
The purpose is:
- to write clean and good code.
- to avoid using frameworks, if possible plain Javascript.
- get advice on the clean frameworks that don't twist JS to obtain class-enabled behaviors.
Here is the Parent prototype of my sandbox:
function Parent(){
}
Parent.prototype = {
"init":function(){
this.name = "anon";
},
"initWithParameters":function(parameters){
this.name = parameters.name ? parameters.name : "anon";
},
"talk": function(){
console.log('Parent is: ' + this.name);
}
}
Now the Child prototype - it adds a "position" property and redefines the behaviors:
function Child(){
Parent.call(this);
}
Child.prototype = new Parent;
Child.prototype.constructor = Child;
Child.prototype.init = function(){
Parent.prototype.call(this);
this.setPosition(0, 0);
}
Child.prototype.initWithParameters = function(parameters){
Parent.prototype.initWithParameters.call(this, parameters);
if(!this.position){
this.position = {x:0, y:0};
}
this.setPosition(parameters.pos.x, parameters.pos.y);
}
Child.prototype.setPosition = function(x, y){
this.position.x = x;
this.position.y = y;
}
Child.prototype.talk = function(){
console.log('Child is: ' + this.name + ' and location is: ' + this.position.x + ', ' + this.position.y);
}
Is this a good practice? Is there no shorthand to avoid writing "Child.prototype." when overriding a property (using a litteral maybe, like the Parent prototype is written).
I know of J. Resig's Class/extend approach. But I'd rather use Javascript as the prototypical language it is, not make it work as a "class-like behaving class-less OO language".
Thanks for your help :-)
In general your approach will work but a better approach will be to replace:
Child.prototype = new Parent;
with:
Child.prototype = Object.create(Parent.prototype);
This way you don't need to call new Parent, which is somewhat an anti-pattern. You could also define new properties directly as follows:
Child.prototype = Object.create(Parent.prototype, {
setPosition: {
value: function() {
//... etc
},
writable: true,
enumerable: true,
configurable: true
}
});
Hope this helps.
Object.create() at MDN
Your approach it is a good pure JavaScript approach. The only get away from tipping "Child.prototype" every time is to put it in a reference variable.
Like:
var children = Child.prototype;
children.init = function(){ /*/someoverridecode*/}
But you are still doing the Child.prototype behind this. You can also define a function that does this for you, see bind of underscore, maybe it suits your needs.
Cheers
I may get deep fried for this suggestion as there are several articles that can argue against some practices in my example, but this has worked for me and works well for clean looking code, stays consistent, minifies well, operates in strict mode, and stays compatible with IE8.
I also like utilizing the prototype methodology (rather than all of the 'extend' or 'apply' styles you see everywhere).
I write out my classes like this. Yes, it looks a lot like an OOP language which you didn't want, but it still adheres to the prototypical model while holding similarities to other familiar languages which makes projects easier to navigate.
This is my style I prefer :) I'm not saying it's the best, but it's so easy to read.
(function(ns) {
var Class = ns.ClassName = function() {
};
Class.prototype = new baseClass();
Class.constructor = Class;
var _public = Class.prototype;
var _private = _public._ = {};
Class.aClassProperty = "aValue";
Class.aClassMethod = function(params) {
}
_public.aMethod = function(params) {
_private.myMethod.call(this, "aParam");
Class.aClassMethod("aParam");
}
_private.myMethod = function(params) {
}
})({});
EDIT:
I went ahead and converted your example this style just to show you what it would look like:
var namespace = {};
(function(ns) {
var Class = ns.Parent = function() {
};
var _public = Class.prototype;
var _private = _public._ = {};
_public.init = function() {
this.name = "anon";
}
_public.initWithParameters = function(parameters) {
this.name = parameters.name ? parameters.name : "anon";
}
_public.talk = function() {
console.log('Parent is: ' + this.name);
}
})(namespace);
(function(ns) {
var Class = ns.Child = function() {
this.position = {x:0, y:0};
};
Class.prototype = new ns.Parent();
Class.constructor = Class;
var _public = Class.prototype;
var _private = _public._ = {};
_public.init = function() {
_public.init.call(this);
this.setPosition(0, 0);
}
_public.initWithParameters = function(parameters) {
_public.initWithParameters.call(this, parameters);
this.setPosition(parameters.pos.x, parameters.pos.y);
}
_public.setPosition = function(x, y) {
this.position.x = x;
this.position.y = y;
}
_public.talk = function() {
console.log('Child is: ' + this.name + ' and location is: ' + this.position.x + ', ' + this.position.y);
}
})(namespace);
Coming from google in 2019.
From the latest MDN documentation, the way to extend prototype is :
function MyClass() {
SuperClass.call(this);
}
// inherit one class
MyClass.prototype = Object.create(SuperClass.prototype);
// mixin another
Object.assign(MyClass.prototype, {
//... your own prototype ...
});
// re-assign constructor
MyClass.prototype.constructor = MyClass;
These are the ways I usually do it:
Using a helper function:
/**
* A clone of the Node.js util.inherits() function. This will require
* browser support for the ES5 Object.create() method.
*
* #param {Function} ctor
* The child constructor.
* #param {Function} superCtor
* The parent constructor.
*/
function inherits (ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false
}
});
};
Then you might simply do:
function ChildClass() {
inherits(this, ParentClass);
// If you want to call parent's constructor:
this.super_.apply(this, arguments);
}
Extending prototype using Lodash
_.assign(ChildClass.prototype, {
value: key
});
Or just give ES6 a chance!
class ParentClass {
constructor() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
this.initializeTime = hours + ':' + minutes + ':' + seconds;
}
}
class ChildClass extends ParentsClass {
constructor() {
super();
console.log(this.initializeTime);
}
}
My example shows several things : Private variable, same parsing argument for the parant and child constructor, rewrite .toString() function try : ""+this. :)
full example with doc :
Output :
Constructor arguments
MM = new Parent("val of arg1", "val of arg2");
Child1 = new childInterface("1", "2");
Child2 = new child2Interface("a", "b");
console.log(MM + "args:", MM.arg1, MM.arg2);
// Parentargs: val of arg1 val of arg2
console.log(Child1 + "args:", Child1.arg1, Child1.arg2);
// childInterfaceargs: 1 2
console.log(Child2 + "args:", Child2.arg1, Child2.arg2);
// child2Interfaceargs: a b
Extend function in child class
MM.init();
// Parent: default ouput
Child1.init();
// childInterface: new output
Child2.init();
// child2Interface: default ouput
Increment variable
MM.increment();
// Parent: increment 1
Child1.increment();
// childInterface: increment 1
Child2.increment();
// child2Interface: increment 1
Child2.increment();
// child2Interface: increment 2
MM.increment();
// Parent: increment 2
console.log("p", "c1", "c2");
// p c1 c2
console.log(MM.value, " " + Child1.value, " " + Child2.value);
// 2 1 2
Private variable
MM.getHidden();
// Parent: hidden (private var) is true
MM.setHidden(false);
// Parent: hidden (private var) set to false
Child2.getHidden();
// child2Interface: hidden (private var) is true
MM.setHidden(true);
// Parent: hidden (private var) set to true
Child2.setHidden(false);
// child2Interface: hidden (private var) set to false
MM.getHidden();
// Parent: hidden (private var) is true
Child1.getHidden();
// childInterface: hidden (private var) is true
Child2.getHidden();
// child2Interface: hidden (private var) is false
Protected variable
function Parent() {
//...
Object.defineProperty(this, "_id", { value: 312 });
};
console.log(MM._id); // 312
MM._id = "lol";
console.log(MM._id); // 312
/**
* Class interface for Parent
*
* #class
*/
function Parent() {
this.parseArguments(...arguments);
/**
* hidden variable
*
* #type {Boolean}
* #private
*/
var hidden = true;
/**
* Get hidden
*/
this.getHidden = () => {
console.log(this + ": hidden (private var) is", hidden);
}
/**
* Set hidden
*
* #param {Boolean} state New value of hidden
*/
this.setHidden = (state) => {
console.log(this + ": hidden (private var) set to", !!state);
hidden = state;
}
Object.defineProperty(this, "_id", { value: "312" });
}
Object.defineProperty(Parent.prototype, "nameString", { value: "Parent" });
/**
* Parse arguments
*/
Parent.prototype.parseArguments = function(arg1, arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
};
/**
* Get className with `class.toString()`
*/
Parent.prototype.toString = function() {
return this.nameString;
};
/**
* Initialize middleware
*/
Parent.prototype.init = function() {
console.log(this + ": default ouput");
};
/**
* Increment value
*/
Parent.prototype.increment = function() {
this.value = (this.value) ? this.value + 1 : 1;
console.log(this + ": increment", this.value);
};
/**
* Class interface for Child
*
* #class
*/
function childInterface() {
this.parseArguments(...arguments);
}
// extend
childInterface.prototype = new Parent();
Object.defineProperty(childInterface.prototype, "nameString", { value: "childInterface" });
/**
* Initialize middleware (rewrite default)
*/
childInterface.prototype.init = function(chatClient) {
console.log(this + ": new output");
};
/**
* Class interface for Child2
*
* #class
*/
function child2Interface() {
this.parseArguments(...arguments);
}
// extend
child2Interface.prototype = new Parent();
Object.defineProperty(child2Interface.prototype, "nameString", { value: "child2Interface" });
//---------------------------------------------------------
//---------------------------------------------------------
MM = new Parent("val of arg1", "val of arg2");
Child1 = new childInterface("1", "2");
Child2 = new child2Interface("a", "b");
console.log(MM + " args:", MM.arg1, MM.arg2);
console.log(Child1 + " args:", Child1.arg1, Child1.arg2);
console.log(Child2 + " args:", Child2.arg1, Child2.arg2);
console.log(" ");
MM.init();
Child1.init();
Child2.init();
console.log(" ");
MM.increment();
Child1.increment();
Child2.increment();
Child2.increment();
MM.increment();
console.log("p", "c1", "c2");
console.log(MM.value, " " + Child1.value, " " + Child2.value);
console.log(" ");
MM.getHidden();
MM.setHidden(false);
Child2.getHidden();
MM.setHidden(true);
console.log(" ");
Child2.setHidden(false);
MM.getHidden();
Child1.getHidden();
Child2.getHidden();
console.log(MM._id);
MM._id = "lol";
console.log(MM._id);
I normally do it like this. I use the class operator now, but there's still a good way to do it in ES3.
Using Node.js utilities
Node.js includes a utility function for this very thing.
const { inherits } = require('util');
function SuperClass () {
this.fromSuperClass = 1;
}
function ExtendingClass () {
this.fromExtendingClass = 1;
}
inherits(ExtendingClass, SuperClass);
const extending = new ExtendingClass();
this.fromSuperClass; // -> 1
this.fromExtendingClass; // -> 1
The above has it's fair share of problems. It doesn't establish the prototypical chain, so it's considered semantically incompatible with the class operator.
Using the Object.create API
Otherwise, you can use Object.create for this.
function Person () {
this.person = true;
}
function CoolPerson () {
Person.call(this);
this.cool = true;
}
CoolPerson.prototype = Object.create(Person);
CoolPerson.prototype.constructor = CoolPerson;
Using a "helper function"
Please note that in the above example that uses the Object.create API, if you do not call Person (the "super class") in the CoolPerson (the extending class), instance properties (and optionally initialization) will not be applied when instantiating Person.
If you want to be more "elegant", you could even create a helper function for this, which might be easier for you.
function extend(BaseClassFactory, SuperClass) {
const BaseClass = BaseClassFactory(SuperClass.prototype, SuperClass);
BaseClass.prototype = Object.assign(BaseClass.prototype, Object.create(SuperClass));
BaseClass.prototype.constructor = BaseClass;
return BaseClass;
}
function SuperClass() {
this.superClass = true;
}
SuperClass.prototype.method = function() {
return 'one';
}
const ExtendingClass = extend((Super, SuperCtor) => {
function ExtendingClass () {
SuperCtor.call(this);
this.extending = true;
}
// Example of calling a super method:
ExtendingClass.prototype.method = function () {
return Super.method.call(this) + ' two'; // one two
}
return ExtendingClass;
}, SuperClass);
const extending = new ExtendingClass();
extending.method(); // => one two
Using ES6's class operator
There's a new class operator in JavaScript that's been released in JavaScript that may make this whole experience more expressive.
class SuperClass {
constructor() {
this.superClass = true;
}
method() {
return 'one';
}
}
class ExtendingClass extends SuperClass {
constructor() {
super();
this.extending = true;
}
method() {
// In this context, `super.method` refers to a bound version of `SuperClass.method`, which can be called like a normal method.
return `${super.method()} two`;
}
}
const extending = new ExtendingClass();
extending.method(); // => one two
Hope this helps.
I need to implement inheritance tree in JavaScript where each node can have more than 1 parent. We have to implement Object.Create and Object.call methods on our own. We are specifically not allowed to use new keyword. Here is what I have so far:
var myObject = {
hash:0,
parents: [],
create: function(args){
//TODO check if not circular
if(args instanceof Array){
for(i=0;i<args.length;i++){
this.parents.push(args[i]);
}
}
return this;
},
call : function(fun,args){
//TODO: dfs through parents
return this[fun].apply(this,args);
},
}
var obj0 = myObject.create(null);
obj0.func = function(arg) { return "func0: " + arg; };
var obj1 = myObject.create([obj0]);
var obj2 = myObject.create([]);
obj2.func = function(arg) { return "func2: " + arg; };
var obj3 = myObject.create([obj1, obj2]);
var result = obj0.call("func", ["hello"]);
alert(result);
//calls the function of obj2 istead of obj0
The problem with this code is that I get a call to obj2's function instead of obj0's. I'm suspecting that create() function should not return this, but something else instead (create instance of itself somehow).
In your current solution, you are not actually creating a new object with your myObject.create() function, you are just using the same existing object and resetting it's parent array. Then, when you define .func() you are overriding that value, which is why func2: appears in your alert.
What you need to do is actually return a brand new object. returning this in your myObject.create() will just return your existing object, which is why things are getting overridden.
To avoid using the new keyword, you'll want to do either functional inheritance or prototypal inheritance. The following solution is functional inheritance:
function myObject (possibleParents) {
//create a new node
var node = {};
//set it's parents
node.parents = [];
//populate it's parents if passed in
if (possibleParents) {
if (possibleParents instanceof Array) {
for (var index = 0; index < possibleParents.length; index++) {
node.parents.push(possibleParents[index]);
}
} else {
node.parents.push(possibleParents);
};
}
//
node.call = function(fun,args) {
return this[fun].apply(this,args);
};
return node;
};
var obj0 = myObject();
obj0.func = function(arg) { return "func0: " + arg; };
var obj1 = myObject([obj0]);
var obj2 = myObject();
obj2.func = function(arg) { return "func2: " + arg; };
var obj3 = myObject([obj1, obj2]);
var result = obj0.call("func", ["hello"]);
alert(result); // this will successfully call "func0: " + arg since you created a new object
I managed fix this problem only by using function instead of variable.
function myObject () {
this.parents = [];
this.setParents = function(parents){
if(parents instanceof Array){
for(i=0;i<parents.length;i++){
this.parents.push(parents[i]);
}
}
};
this.call = function(fun,args) {
return this[fun].apply(this,args);
};
}
var obj0 = new myObject();
obj0.func = function(arg) { return "func0: " + arg; };
var obj2 = new myObject();
obj2.func = function(arg) { return "func2: " + arg; };
var result = obj0.call("func", ["hello"]);
alert(result);
I lately was experimenting with the object serialization in JavaScript. I have already been looking through some of the questions concerning the serialization and deserialization of predefined object in Javascript, but I am looking for a more general solution. An example of this would be:
function anObject(){
var x = 1;
this.test = function(){return x;};
this.add = function(a){x+a;};
}
var x = new anObject();
x.add(2);
console.log(x.test());
>>> 3
var y = deserialize(serialize(x));
console.log(y.test());
>>> 3
Is there a way to serialize this object and deserialize it, such that the deserialized object still have access to the local variable x without the use of the prototype of that object (like in this solution)?
I have already tried by just storing the function as a string and evaluating it again, but then the state of an object can not be saved.
What you are trying to do is not possible without code introspection and code re-writing which I think is not a good idea. However, what about something like this?
function AnObject() {
var x = 1;
this.x = function () { return x; };
this.addToX = function (num) { x += num; };
this.memento = function () {
return { x: x };
};
this.restoreState = function (memento) {
x = memento.x;
};
}
var o = new AnObject();
o.addToX(2);
o.x(); //3
var serializedState = JSON.stringify(o.memento()),
o = new AnObject();
o.restoreState(JSON.parse(serializedState));
o.x(); //3
However, please note that having priviledged members comes at a great cost because you lose the benefits of using prototypes. For that reason I prefer not enforcing true privacy and rely on naming conventions such as this._myPrivateVariable instead (unless you are hiding members of a module).
Thanks for the responses. While the answer from plalx works perfectly for specific objects, I wanted to have something more general which just works for any object you throw at it.
Another solution one can use is something like this:
function construct(constructor, args, vars) {
function Obj() {
var variables = vars
return constructor.apply(this, args);
}
Obj.prototype = constructor.prototype;
return new Obj();
}
function addFunction(anObject, aFunction, variables) {
var objectSource = anObject.toString();
var functionSource = aFunction.toString();
objectSource = objectSource.substring(0,objectSource.length-1);
var functionName = functionSource.substring(9, functionSource.indexOf('('));
var functionArgs = functionSource.substring(functionSource.indexOf('('), functionSource.indexOf('{')+1);
var functionBody = functionSource.substring(functionSource.indexOf('{')+1, functionSource.length);
return objectSource + "this." + functionName + " = function" +
functionArgs + "var variables = " + variables + ";\n" + functionBody + "}";
}
function makeSerializable(anObject) {
var obj = JSON.stringify(anObject, function(key, val) {
return ((typeof val === "function") ? val+'' : val);
});
var variables = [];
while(obj.indexOf("var") > -1) {
var subString = obj.substring(obj.indexOf("var")+3, obj.length-1);
while (subString[0] == " ")
subString = subString.replace(" ", "");
var varEnd = Math.min(subString.indexOf(" "), subString.indexOf(";"));
var varName = subString.substring(0, varEnd);
variables.push(varName);
obj = obj.replace("var","");
}
var anObjectSource = addFunction(anObject,
function serialize(){
var vars = [];
console.log("hidden variables:" + variables);
variables.forEach(function(variable) {
console.log(variable + ": " + eval(variable));
vars += JSON.stringify([variable, eval(variable)]);
});
var serialized = [];
serialized.push(vars);
for (var func in this){
if (func != "serialize")
serialized.push([func, this[func].toString()]);
}
return JSON.stringify(serialized);
},
JSON.stringify(variables));
anObject = Function("return " + anObjectSource)();
var params = Array.prototype.slice.call(arguments);
params.shift();
return construct(anObject, params, variables);
}
This allows you to serialize all elements of any object, including the hidden variables. The serialize() function can then be replaced by a custom string representation for the hidden variables, which can be used when deserializing the string representation to the object.
usage:
function anObject(){
var x = 1;
var y = [1,2];
var z = {"name": "test"};
this.test = function(){return x;};
this.add = function(a){x+a;};
}
var test = makeSerializable(anObject)
test.serialize()
>>>["[\"x\",1][\"y\",[1,2]][\"z\",{\"name\":\"test\"}]",["test","function (){return x;}"],["add","function (a){x+a;}"]]
Is there a small, lightweight solution for javascript class inheritance that will work well on both client and server side (node.js)? I'm not wanting a big library, just something that will allow me to declare a constructor and some methods, then have the ability for a class to inherit that.
John Resig outlines a simple inheritance framework in about 25 lines of code here. I have seen it used to good effect.
You can use it like this:
var Vehicle = Class.extend({
init: function(wheels) {
this.wheels = wheels;
}
});
var Truck = Vehicle.extend({
init: function(hp, wheels) {
this.horsepower = hp;
this._super(wheels);
},
printInfo: function() {
console.log('I am a truck and I have ' + this.horsepower + ' hp.');
}
});
var t = new Truck(4, 350);
t.printInfo();
take a look at https://github.com/ded/klass
I created this small library to use an ExtJs Style ClassManager. It's quite simple yet, but very flexible.
Install via node.js
npm install esf-core
Sample
Esf.define('A', {
a: null,
constructor: function (a) {
// Save var
this.a = a;
// Heyho
console.log('A');
},
foo: function (b) {
console.log('foo - ' + b);
}
});
Esf.define('B', {
b: null,
constructor: function (a, b) {
// Call super constructor
this.callParent(a);
// Save var
this.b = b;
// Heyho
console.log('B');
},
foo: function () {
this.callParent('bar');
}
}, {
extend: 'A'
});
// Use
var b = new B(1, 2);
// or
var b = Esf.create('B', 1, 2);
/*
* Output:
* A
* B
* foo - bar
*/
b.foo();
Repository
https://bitbucket.org/tehrengruber/esf-js-core
I've seen the prototype library used successfully.
I think this is much better than the init hax in the simple inheritance fw:
(function() {
var core = {
require : function(source) {
if ( typeof (source) != "object" || !source)
throw new TypeError("Object needed as source.");
for (var property in source)
if (source.hasOwnProperty(property) && !this.prototype.hasOwnProperty(property))
this.prototype[property] = source[property];
},
override : function(source) {
if ( typeof (source) != "object" || !source)
throw new TypeError("Object needed as source.");
for (var property in source)
if (source.hasOwnProperty(property))
this.prototype[property] = source[property];
},
extend : function(source) {
var superClass = this;
var newClass = source.hasOwnProperty("constructor") ? source.constructor : function() {
superClass.apply(this, arguments);
};
newClass.superClass = superClass;
var superClone = function() {
};
superClone.prototype = superClass.prototype;
newClass.prototype = new superClone();
newClass.prototype.constructor = newClass;
if (source)
newClass.override(source);
return newClass;
}
};
core.require.call(Function, core);
Function.create = function (source){
var newClass = source.hasOwnProperty("constructor") ? source.constructor : function() {};
newClass.override(source);
return newClass;
};
})();
The vehicle example with this:
var Vehicle = Function.create({
constructor : function(wheels) {
this.wheels = wheels;
}
});
var Truck = Vehicle.extend({
constructor : function(hp, wheels) {
this.horsepower = hp;
Vehicle.call(this, wheels);
},
printInfo : function() {
console.log('I am a truck and I have ' + this.horsepower + ' hp.');
}
});
var t = new Truck(4, 350);
t.printInfo();
I created a very lightweight library that works in-browser and in node.js. Its a super easy-to-use, bloatless library:
https://github.com/fresheneesz/proto
Example:
var Person = proto(function() { // prototype builder
this.init = function(legs, arms) { // constructor
this.legs = legs
this.arms = arms
}
this.getCaughtInBearTrap = function() { // instance method
this.legs -= 1
}
this.limbs = function() {
return this.arms + this.legs
}
})
var Girl = proto(Person, function() { // inheritance
this.haveBaby = function() {
return Person(2,2)
}
})
var g = Girl(2,2) // instantiation
g.getCaughtInBearTrap()
console.log("Girl has "+g.limbs()+" limbs")
console.log(": (")