Javascript OOP Semi-circular inheritance - javascript

I try to resolve in a cleaner way that I made the following problem :
I've got two class A and B where A inherit from B.
What I want is when I call a method of the class B via the class A I get a new instance of B and then the method is executed, and keep the inheritance of instance A.
Note that the methods of B must return 'this' for chaining.
Example :
var classA = new class A();
classA.setName("John");
var result1 = classA.methodOfClassB().otherMethodOfClassB();
var result2 = classA.methodOfClassB().otherMethodOfClassB();
var result3 = result1.otherMethodOfClassB();
console.log(result1 === result2); //false
console.log(result1 === result3); //true
//Call a method of class A from class B
console.log(result1.methodOfClassAGetName()); //John
console.log(result1.methodOfClassAGetName()); //John
My implementation
function classA() {
var self = this;
self.methAclassA = function() {
/* ... */
console.log(this.methAclassB());
};
classB.call(self, true);
return (self);
}
function classB(isNew) {
var self = this;
var _getNewInstance = function() {
var instance = new classB(false);
instance.__proto__ = self;
return (instance);
};
self.methAclassB = function() {
if (isNew) {
return (_getNewInstance().methAclassB());
}
/* ... */
return (self);
};
}
Thank you in advance !
(Sorry for the English, this is not my first language)

Related

Returning a function and using this keyword in Javascript

I am new to JavaScript and am trying to understand the working of the famous this keyword. I have the following code -
class A {
variableA = 1;
function aFunc(){
return function B(){
// Use variableA and variableC here
}
}
}
class C {
variableC=2;
cFunc;
}
function updateC() {
let a = new A();
let c = new C();
c.cFunc = a.aFunc();
c.cFunc();
}
One possible solution is to store A's this in some other variable. Is there a better way to handle this case?
Try this
class A {
constructor() {
var A_this = this;
A_this.data = 'Class A';
this.someFunc = function someFunc(){
return function B(){
var B_this = this;
// use A's this A_this
//and B's this B_this
B_this.data = 'Function B';
}
}
}
}
var a = new A;
var b = a.someFunc()
var bObj = new b();
console.log(a.data, bObj.data);//Class A Function B
You can check this
how to do `var self = this` inside es6 class?
. My own question asked almost 4, 5 years back

Create only one instance of constructor function?

I have a part of plugin which uses private variables and exposes public method :
JSBIN 1
function myWorld()
{
var myPrivate=1;
this.do1=function (){alert(myPrivate);} ;
}
var a=new myWorld();
a.do1() //1
alert(a.myPrivate); //undefined (as it should be)
But I want to prevent doing this again : new myWorld();
The only option I know is with object literal :
JSBIN 2
var myWorld=
{
myPrivate:1,
do1:function (){alert(this.myPrivate);}
}
alert(myWorld.myPrivate); //1 ( ouch....)
myWorld.do1() //1
Question
How can encapsulate private fields and still prevent uses from myWorld to be instanced >1 times ?
Closures are a great tool to define the scope:
var myWorld= (function(){
var myPrivate = 1;
return {
do1:function (){alert(myPrivate);}
}
}());
myWorld.do1();
You might want to check out the free Learning JavaScript Design Patterns book
Try something along these lines:
(function(){
var instanciated = false;
window.myWorld = function() {
if( instanciated) throw new Error("myWorld can only be instanciated once!");
instanciated = true;
var myPrivate = 1;
this.do1 = function(){alert(myPrivate);};
}
})();
You can hide the private variable inside an IIFE:
var myWorld = (function() {
var myPrivate = 1;
return { ... };
}());
var a = new function myWorld()
{
var myPrivate=1;
this.do1=function (){alert(myPrivate);} ;
}
This makes myWorld available only inside the function. If you don't event want it accessable there, then remove the name.
You could use a singleton pattern to maintain one instance of the object. Something like:
(function (global) {
var _inst;
global.myWorld = function () {
if (_inst) throw new Error("A myWorld instance already exists. Please use myWorld.getInstance()");
_inst = this;
};
global.myWorld.prototype = {
do1: function() {
console.log("do1");
}
};
global.myWorld.getInstance = function() {
if (_inst) return _inst;
return new myWorld();
};
}(window));
var world = new myWorld();
var world2 = myWorld.getInstance();
console.log(world === world2); // true
var world3 = new myWorld(); // throws Error

Static variables with John Resig's simple class pattern?

I'm referring to this article.
In it, he defines a function that looks something like this:
function makeClass() {
return function _class() {
if(this instanceof _class) {
if(typeof this.init === 'function') {
this.init.apply(this, arguments);
}
} else {
throw new Error('Constructor called as a function');
}
};
}
And then you can use it with something like this:
var MyClass = makeClass();
MyClass.prototype = {
init: function(width, height) { ... },
clear: function(ctx) {... },
draw: function(ctx) { ... }
}
But now I want to initialize some static variables that should be shared across all instances. How do I do that?
Well, the easiest approach is to define a static variable as a prototype property:
MyClass.prototype.xxx: 3, // ...
var t1 = new MyClass();
console.log(t1.xxx); // 3
... but it won't behave as static properties in other languages usually do:
var t2 = new MyClass();
t2.xxx = 5;
console.log(t1.xxx); // still 3 :(
The other way around is to use the fact that properties might be attached to functions as well:
MyClass.xxx = 3;
... but that narrows the ways we can use this property (it can't be called by t1.xxx from the previous examples).
There's another way, though. One can define static properties as variables, local to init method, accessible by methods, defined... in this init method as well. ) Like this.
init: function() {
var xxx = 3;
MyClass.prototype.getXXX = function() {
return xxx;
};
MyClass.prototype.setXXX = function(newXXX) {
xxx = newXXX;
}
}
Then all one can use this property simply by this:
var t1 = new MyClass();
var t2 = new MyClass();
console.log(t1.getXXX()); // 3
console.log(t2.getXXX()); // 3
t1.setXXX(5);
console.log(t1.getXXX()); // 5 now
console.log(t2.getXXX()); // 5 as well, behold the power of closures!
And here's a fiddle used.
UPDATE: this approach is better be used, I suppose, when we need to work with a (sort of) container of the static class data, that is to be shared by all objects - but we don't know exactly what can actually be stored in this container. Then we use just two functions - getStatic and setStatic - to store and retrieve data by string keys or some other identifiers. It may seem a bit confusing, and it is, but I think it may be worth an effort. )
Just add it to MyClass itself.
MyClass.myVariable = 42;
It's not really static in the Java/C# sense, but gives you the same effect.
I "solved" this problem by using a naming convention.
I wanted the convenience of the Class.extend({ }) syntax, but also a way to declare "static" properties within it.
I opted for a leading underscore to declare a static property, although you could do whatever you liked.
Usage:
var myClass = Class.extend({
_staticProperty: 1337
, instanceProperty: 'foo'
, instanceMethod: function() { }
, ctor: function() {
this.base();
}
});
note I've renamed init and this._super() from the original code
And the code:
/* Simple JavaScript Inheritance
* Modified by Andrew Bullock http://blog.muonlab.com to add static properties
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
(function () {
var initializing = false, fnTest = /xyz/.test(function () { xyz; }) ? /\bbase\b/ : /.*/;
// The base Class implementation (does nothing)
this.Class = function () { };
// Create a new Class that inherits from this class
Class.extend = function (prop) {
var base = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// The dummy class constructor
function Class() {
// All construction is actually done in the ctor method
if (!initializing && this.ctor)
this.ctor.apply(this, arguments);
}
// Copy static properties from base
for (var name in this) {
if (name.substr(0, 1) == '_')
Class[name] = this[name];
}
// Copy the properties over onto the new prototype
for (name in prop) {
// Check if we're overwriting an existing function
if (typeof prop[name] == "function" && typeof base[name] == "function" && fnTest.test(prop[name])) {
prototype[name] = (function(name, fn) {
return function() {
var tmp = this.base;
// Add a new .base() method that is the same method
// but on the super-class
this.base = base[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this.base = tmp;
return ret;
};
})(name, prop[name]);
} else if (name.substr(0, 1) == '_') {
Class[name] = prop[name];
} else {
prototype[name] = prop[name];
}
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
If you don't care about browser support, you could also use a WeakMap of constructor/static properties pairs. Here's the idea: http://jsfiddle.net/DfNNU/2/. This requires MyClass.prototype.constructor, which you should not discard. So, you'd need to add back constructor: MyClass to the prototype.
var statics = (function() {
var map = new WeakMap;
return function(inst) {
var ctor = inst.constructor;
return map.get(ctor) || map.set(ctor, {});
};
})();
Use it like:
var a = function() {};
var b = function() {};
var inst1 = new a;
var inst2 = new a;
var inst3 = new b;
statics(inst1).foo = 123;
statics(inst3).foo = 456;
console.log( statics(inst1).foo ); // 123
console.log( statics(inst2).foo ); // 123
console.log( statics(inst3).foo ); // 456
I've modified John Resig's class to provide copy over the parent's static members to the new class, which adds this:
for (var name in this) {
if (!Class[name]) {
Class[name] = this[name];
}
}
Here's a fiddle.
// This is a modified version of John Resig's simple inheritence class to add copying of static methods
// The new code is the for loop commented with "add in the static members"
/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
this.Class = function(){};
// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
//add in the static members
for (var name in this) {
if (!Class[name]) {
Class[name] = this[name];
}
}
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
function addText(text) {
document.getElementById('greetings').innerHTML = document.getElementById("greetings").innerHTML + '<br>' + text;
}
//parent class with a prototype method and two static methods
var Parent = Class.extend({
hello: function () {
addText('parent.hello');
}
});
Parent.static = function() {
addText('Parent.static');
}
Parent.overrideStatic = function() {
addText('Parent.overrideStatic');
}
//child class that overrides one of the parent's static methods
var Child = Parent.extend();
Child.overrideStatic = function() {
addText('Child.overrideStatic');
}
var parent = new Parent();
parent.hello();
Parent.static();
var child = new Child();
child.hello(); //should output parent.hello
Child.static(); //should output Parent.static
Child.overrideStatic();
<div id="greetings"></div>
Pass in an optional list of static members in the call to 'extend'. This method adds the static properties (if any) to a 'statics' attribute on the constructor function.
Code Changes
Changes as follows. These lines added just after the 'dummy class constructor' code:
if(staticProp) {
Class.statics = [];
for (var name in staticProp) {
!Class.statics[name] && (Class.statics[name] = staticProp[name]);
}
}
An additional argument 'staticProp' added when type is declared in order to allow introduction of static members at this stage:
Class.extend = function(prop,staticProp) {
A fiddle can be found here, includes some tests.
Usage Examples
Can define statics at type declaration time like so using the second optional constructor argument:
var A = Class.extend({},{myStatic:1});
Can access/define statics inside an instance method:
var B = Class.extend({test:function(){B.statics.myStatic=2;}});
Or from outside an instance:
A.statics.myStatic=3;
Example with requirejs:
Put Class.js in the baseUrl folder. Example new class definition. Not mandatory to name the file of the new class the same as the 'var C' (i.e. C.js) but probably better for readability so references to the C name within the class's methods are aligned to any external references to its static members:
define(['Class'],function($) {
var C = Class.extend({
init: function(params){
C.statics.myStatic++; // access static data
}
},{
myStatic: 123
});
return C;
});
Another class in D.js refers to static data in class C:
define(['Class', 'C'],function($,C) {
var D = Class.extend({
init: function(params){
C.statics.myStatic++; // static data of another class
}
},{});
return D;
});

Javascript prototypal inheritance and OOP

I'm creating an application that allows a user to create widgets. There are several different types of widgets, and I have defined them using protypal inheritance. i.e.
//the base widget that all widgets inherit from
var Widget = function(){}
Widget.prototype.someFunction = function(){}
//widget type A
var A = function(){}
A.prototype = new Widget();
//widget type B
var B = function(){}
B.prototype = new Widget();
I have discovered that it will be convenient to add a method on the base class that can create a new widget instance of the same type. i.e.
//the base widget
var Widget = function(){};
Widget.prototype.clone = function(){
switch(this.type){
case 'A':
return new A();
break;
case 'B':
return new B();
break;
default:
break;
}
};
Which would allow me to get a new widget of the same type using the following code:
var widgetTypeA = new A();
var cloneOfWidgetTypeA = widgetTypeA.clone();
My concern is that the base widget now has to be explicitly aware of each of the types of widgets that inherit from it. Does this violate any principles of good OOP?
Widget.prototype.clone = function() {
var constructor = window[this.type];
return new constructor();
};
Assuming that all your subclasses are declared as globals of course.
But honestly I would out those sub classes in the Widget namespace, and access them through it rather than making everything global.
Widget.A = function(){};
Widget.A.prototype = new Widget();
Widget.prototype.clone = function() {
var constructor = Widget[this.type];
return new constructor();
};
Given that your constructors are globals, you could do something like:
var global = this;
Widget.prototype.clone = function() {
if (global[this.type])
return new global[this.type]();
};
Provided each instance has a type property whose value is the name of the constructor. Or you could fix the constructor property of constructor's prototype and do:
Widget.prototype.clone = function() {
return new this.constructor();
};
function A() { };
A.prototype = new Widget();
A.prototype.constructor = A;
var a = new A();
var aa = a.clone();
However, that assumes that you don't have any parameters to pass. If you do have parameters to pass, then you likely have to know which type you are making and so can call the correct constructor anyway.
If ECMA5 is supported:
use Object.create(Object.getPrototypeOf(this));
If ECMA5 is not supported:
create an anonymous function
set the prototype of the anonymous function to the non-standard attribute this.__proto__
Example:
var Widget = function() { };
Widget.prototype.clone = function() {
/*
Non-ECMA5:
var newClone = function() {};
newClone.prototype = this.__proto__;
return new newClone();
*/
// ECMA5
return Object.create(Object.getPrototypeOf(this));
}
var A = function() { };
A.prototype = new Widget();
A.prototype.name = "I'm an A";
var B = function() { };
B.prototype = new Widget();
B.prototype.name = "I'm a B";
var x1 = new A();
var y1 = x1.clone();
console.log("y1 should be A: %s", y1.name);
var x2 = new B();
var y2 = x2.clone();
console.log("y2 should be B: %s", y2.name);
The information you need is already available in the constructor property. However, overwriting prototype will lose it as I recently explained here.
Using my own class implementation for ECMAScript version 3 or version 5, your example would look like this:
var Widget = Class.extend({
someFunction : function() {
alert('someFunction executed');
},
clone : function() {
return new this.constructor;
}
});
var A = Widget.extend();
var B = Widget.extend({
constructor : function(arg) {
Widget.call(this); // call parent constructor
this.arg = arg;
},
// override someFunction()
someFunction : function() {
alert('someFunction executed, arg is ' + this.arg)
},
// clone() needs to be overriden as well:
// Widget's clone() doesn't know how to deal with constructor arguments
clone : function() {
return new this.constructor(this.arg);
}
});
var a = new A;
var a2 = a.clone();
a2.someFunction();
var b = new B(42);
var b2 = b.clone();
b2.someFunction();

Calling method using JavaScript prototype

Is it possible to call the base method from a prototype method in JavaScript if it's been overridden?
MyClass = function(name){
this.name = name;
this.do = function() {
//do somthing
}
};
MyClass.prototype.do = function() {
if (this.name === 'something') {
//do something new
} else {
//CALL BASE METHOD
}
};
I did not understand what exactly you're trying to do, but normally implementing object-specific behaviour is done along these lines:
function MyClass(name) {
this.name = name;
}
MyClass.prototype.doStuff = function() {
// generic behaviour
}
var myObj = new MyClass('foo');
var myObjSpecial = new MyClass('bar');
myObjSpecial.doStuff = function() {
// do specialised stuff
// how to call the generic implementation:
MyClass.prototype.doStuff.call(this /*, args...*/);
}
Well one way to do it would be saving the base method and then calling it from the overriden method, like so
MyClass.prototype._do_base = MyClass.prototype.do;
MyClass.prototype.do = function(){
if (this.name === 'something'){
//do something new
}else{
return this._do_base();
}
};
I'm afraid your example does not work the way you think. This part:
this.do = function(){ /*do something*/ };
overwrites the definition of
MyClass.prototype.do = function(){ /*do something else*/ };
Since the newly created object already has a "do" property, it does not look up the prototypal chain.
The classical form of inheritance in Javascript is awkard, and hard to grasp. I would suggest using Douglas Crockfords simple inheritance pattern instead. Like this:
function my_class(name) {
return {
name: name,
do: function () { /* do something */ }
};
}
function my_child(name) {
var me = my_class(name);
var base_do = me.do;
me.do = function () {
if (this.name === 'something'){
//do something new
} else {
base_do.call(me);
}
}
return me;
}
var o = my_child("something");
o.do(); // does something new
var u = my_child("something else");
u.do(); // uses base function
In my opinion a much clearer way of handling objects, constructors and inheritance in javascript. You can read more in Crockfords Javascript: The good parts.
I know this post is from 4 years ago, but because of my C# background I was looking for a way to call the base class without having to specify the class name but rather obtain it by a property on the subclass. So my only change to Christoph's answer would be
From this:
MyClass.prototype.doStuff.call(this /*, args...*/);
To this:
this.constructor.prototype.doStuff.call(this /*, args...*/);
if you define a function like this (using OOP)
function Person(){};
Person.prototype.say = function(message){
console.log(message);
}
there is two ways to call a prototype function: 1) make an instance and call the object function:
var person = new Person();
person.say('hello!');
and the other way is... 2) is calling the function directly from the prototype:
Person.prototype.say('hello there!');
This solution uses Object.getPrototypeOf
TestA is super that has getName
TestB is a child that overrides getName but, also has
getBothNames that calls the super version of getName as well as the child version
function TestA() {
this.count = 1;
}
TestA.prototype.constructor = TestA;
TestA.prototype.getName = function ta_gn() {
this.count = 2;
return ' TestA.prototype.getName is called **';
};
function TestB() {
this.idx = 30;
this.count = 10;
}
TestB.prototype = new TestA();
TestB.prototype.constructor = TestB;
TestB.prototype.getName = function tb_gn() {
return ' TestB.prototype.getName is called ** ';
};
TestB.prototype.getBothNames = function tb_gbn() {
return Object.getPrototypeOf(TestB.prototype).getName.call(this) + this.getName() + ' this object is : ' + JSON.stringify(this);
};
var tb = new TestB();
console.log(tb.getBothNames());
function NewClass() {
var self = this;
BaseClass.call(self); // Set base class
var baseModify = self.modify; // Get base function
self.modify = function () {
// Override code here
baseModify();
};
}
An alternative :
// shape
var shape = function(type){
this.type = type;
}
shape.prototype.display = function(){
console.log(this.type);
}
// circle
var circle = new shape('circle');
// override
circle.display = function(a,b){
// call implementation of the super class
this.__proto__.display.apply(this,arguments);
}
If I understand correctly, you want Base functionality to always be performed, while a piece of it should be left to implementations.
You might get helped by the 'template method' design pattern.
Base = function() {}
Base.prototype.do = function() {
// .. prologue code
this.impldo();
// epilogue code
}
// note: no impldo implementation for Base!
derived = new Base();
derived.impldo = function() { /* do derived things here safely */ }
If you know your super class by name, you can do something like this:
function Base() {
}
Base.prototype.foo = function() {
console.log('called foo in Base');
}
function Sub() {
}
Sub.prototype = new Base();
Sub.prototype.foo = function() {
console.log('called foo in Sub');
Base.prototype.foo.call(this);
}
var base = new Base();
base.foo();
var sub = new Sub();
sub.foo();
This will print
called foo in Base
called foo in Sub
called foo in Base
as expected.
Another way with ES5 is to explicitely traverse the prototype chain using Object.getPrototypeOf(this)
const speaker = {
speak: () => console.log('the speaker has spoken')
}
const announcingSpeaker = Object.create(speaker, {
speak: {
value: function() {
console.log('Attention please!')
Object.getPrototypeOf(this).speak()
}
}
})
announcingSpeaker.speak()
No, you would need to give the do function in the constructor and the do function in the prototype different names.
In addition, if you want to override all instances and not just that one special instance, this one might help.
function MyClass() {}
MyClass.prototype.myMethod = function() {
alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
MyClass.prototype.myMethod_original.call( this );
alert( "doing override");
};
myObj = new MyClass();
myObj.myMethod();
result:
doing original
doing override
function MyClass() {}
MyClass.prototype.myMethod = function() {
alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
MyClass.prototype.myMethod_original.call( this );
alert( "doing override");
};
myObj = new MyClass();
myObj.myMethod();

Categories

Resources