Efficient way for Javascript inheritance - javascript

I have two javascript classes as
class1 = function(opt) {
function abc () {
}
function def () {
}
function xyz () {
}
};
class2 = function(opt) {
function abc () {
}
function def () {
}
function lmn () {
}
};
These two classes contain some common methods like (abc, def) and some specific methods like (lmn, xyz). Can anybody suggest me how to apply inheritance to this situation effectively, so that I can have common methods in one file and specific methods in respective files. I tried prototype method, but this is not working. So is there any other way to this.
Thanks.

Depending on whether these classes just share behavior (interface) or are actually subclasses of a common class, you should use either a mixin or prototypal inheritance respectively.
An example for prototypes:
function BaseClass () {
}
BaseClass.prototype = {
abc: function () {
},
def: function () {
}
};
function class1 () {
}
class1.prototype = new BaseClass();
class1.prototype.xyz = function () {
};
function class2 () {
}
class2.prototype = new BaseClass();
class2.prototype.lmn = function () {
};
And an example of mixins:
function BaseMixin (object) {
object.abc = BaseMixin.prototype.abc;
object.def = BaseMixin.prototype.def;
}
BaseMixin.prototype = {
abc: function () {
},
def: function () {
}
};
function class1 () {
BaseMixin(this);
}
class1.prototype = {
xyz: function () {
}
};
function class2 () {
BaseMixin(this);
}
class2.prototype = {
lmn: function () {
}
};

Javascript dont have classes
But you can systemise your code.Javascript inheritance is totally different from that of othe oop languages.
Here,We use prototypes and constructors.
**prototype==>**In simple words,I am used for extension purpose
**constructors==>**I am used for creating multiple instances.Any function can be used as a constructor by using the new keyword.
Just sample codes for understanding.
SAMPLE 1:BY USING OBJECT LITERAL
var Myobject = {
Function_one: function()
{
//some code
Myobject.function_three();
},
Function_two: function()
{
//some code
Myobject.function_three();//lets say i want to execute a functin in my object ,i do it this way...
},
Function_three: function()
{
//some code
}
};
window.onload = Myobject.Function_one //this is how you call a function which is in an object
SAMPLE 2:BY USING PROTOTYPE
function function_declareVariable()
{
this.a= 10; //i declare all my variable inside this function
this.b= 20;
}
function_declareVariable.prototype.Function_one = function()
{
//some code
Myobject.Function_three();
};
function_declareVariable.prototype.Function_two = function()
{
Myobject.Function_three();
};
function_declareVariable.prototype.Function_three = function()
{
alert(Myobject.a or Myobject.b)
//some code
};
var Myobject = new function_declareVariable();//this is how i instantiate
REFER 1:what are constructors ,prototypes
REFER 2:prototypal inheritance

Related

How can I call another object's function in JavaScript?

In the code below, I want to use One's reference to Two to call its saySomething() function. When I try it this way, I get this error:
Uncaught ReferenceError: other is not defined.
How can I change my code to make it work?
class One
{
constructor (other)
{
this.other = other;
}
doSomething ()
{
this.other.saySomething();
}
}
class Two
{
saySometing ()
{
console.log("hi");
}
}
const t = new Two();
const o = new One(t);
o.doSomething();
You have a typo in your saySometing() declaration. It should be saySomething().
Not sure what would be the best pattern with JavaScript classes but prototypes (which is what classes use under the hood anyway) will allow you to do so:
var One = function() {
Two.prototype.saySomething();
}
One.prototype = {
}
var Two = function() {
}
Two.prototype = {
saySometing: function() {
console.log("hi");
}
}
const t = new One();

How can an inner object reference its parent's objects at declaration?

JSFiddle: https://jsfiddle.net/dyncmuks/1/
var someObject = {
run: function(str) {
console.log("running");
this.methods[str]();
},
method1: function() {
console.log("method 1");
},
method2: function() {
console.log("method 2");
},
methods: {
one: this.method1, //This == the 'methods' object
two: this.method2 //I want to refer to the 'someObject' object
}
};
Is there a way to make this work?
I could move the method declarations to inside the methods object, but that'll require some refactoring on the actual code I'm working on, and I just want to get this to work).
As was mentioned, there is no way to reference to parent properties from a nested objects in object literal.
But I would suggest some alternative with modular pattern.
The following approach generates and returns the object someObject with a single public method run. The "main" object marked as private object and it can't be modified or be accessible by someone.(it's safe now). The getMethods method 'implicitly' returns the list(object) of all methods of 'main' object.
var someObject = (function(){
var privateObj = {
method1: function() {
console.log("method 1");
},
method2: function() {
console.log("method 2");
},
method3: function() {
console.log("method 3");
},
getMethods : function(){
var self = this;
return {
one: self.method1,
two: self.method2,
three: self.method3
};
}
};
return {
run: function(str) {
console.log("running");
privateObj.getMethods()[str]();
}
};
}());
https://jsfiddle.net/xnbe510b/
You could by simply restructuring this a bit and using "bind" to bind "this" in the object constructor to the functions which should have reference to it.
function someObject() {
this.methods = {
method1: function() {
console.log(this);
console.log("method 1");
},
method2: this.method2.bind(this)
}
}
someObject.prototype.run = function(str) {
console.log("running");
this.methods[str]();
}
someObject.prototype.method2 = function() {
console.log(this);
console.log("method 2");
}
var a = new someObject();
a.run("method1");
a.run("method2");
I don't think if that's exactly what are you looking for, but I found out that you can achieve it using getters.
For example:
var test = {
someProperty: true,
get somePropertyReference() {
return this.someProperty;
}
};
console.log(test.somePropertyReference);

Check if a private function exists inside an object in JavaScript

How can I check if a private function exist inside an object?
var myObj = function(){
var myFunc = function(){};
var init = function(){
//has myFunc been defined?
}
}
I know that I can do this:
if (typeof myFunc == 'function') {
//myFunc exist
}
But this is checking the global scope.
How can I limit this to my objects scope?
Here is the most simplified case that i need:
var myComponent = function () {
var exportExcel = function () {
};
this.export = function (type) {
if('export'+type is a private function in this scope){
window["export"+type]()//but in local scope;
}
}
};
And here is my work around for now :
var myComponent = function () {
var Exports = {
Excel: function () {
}
};
this.export = function (type) {
if (Exports.hasOwnProperty(type)) {
Exports[type]();
} else {
alert('This Export type has not been implemented Yet ! or it never will ... how knows? well i don\'t ...');
}
}
};
As you probably noticed:
function myFunc () {};
function myObj () {
function init () {
if (myFunc) // passes
};
}
You could cheat a bit :-|
function myObj () {
var isdef = { myFunc: true };
function myFunc () {};
function init () {
if (isdef.myFunc) // do something
};
}
I wonder why one would do that though.
Bases on the extra information given, the most practical pattern is what you're calling the "temporary workaround": keeping your functions in a private object, keyed by type.
var myComponent = function () {
var exporters = Object.create(null, {
"Excel": function () {
// do magic export here
}
});
this.export = function (type) {
if (type in exporters) {
// defined locally
return exporters[type].call(this); // binding is optional
} else {
// no export for you!
}
}
};
This prevents two things:
Referencing the function via string composition,
Querying the global scope (or, actually, any scope in between your component and the global scope).
This may not be your design principle, you could further extend this code to allow for adding / removing exporters.

Minimize object

I have a code like this:
var methods = {
collapse: function(element) {
modify(element);
},
other_method: function() {
// ...
}
};
function modify(element)
{
console.log('collapse method');
}
Is it possible to minify collapse method to one line? So it should always call modify function.
Try this:
var methods = {
collapse: modify,
other_method: function() {
// ...
}
};
function modify(element) {
console.log('collapse method');
}
Because we have function declaration (not expression), modify is visible when you declare the object methods. The thing which is done here is just setting collapse to be equal to modify's reference.
This is the same as:
var modify = function (element) {
console.log('collapse method');
}
var methods = {
other_method: function() {
// ...
}
};
methods.collapse = modify;

Javascript: best Singleton pattern [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Simplest/Cleanest way to implement singleton in JavaScript?
I'm using this pattern for singletons, in the example the singleton is PlanetEarth:
var NAMESPACE = function () {
var privateFunction1 = function () {
privateFunction2();
};
var privateFunction2 = function () {
alert('I\'m private!');
};
var Constructors = {};
Constructors.PlanetEarth = function () {
privateFunction1();
privateFunction2();
};
Constructors.PlanetEarth.prototype = {
someMethod: function () {
if (console && console.log) {
console.log('some method');
}
}
};
Constructors.Person = function (name, address) {
this.name = name;
this.address = address;
};
Constructors.Person.prototype = {
walk: function () {
alert('STOMP!');
}
};
return {
Person: Constructors.Person, // there can be many
PlanetEarth: new Constructors.PlanetEarth() // there can only be one!
};
}();
Since PlanetEarth's constructor remains private, there can only be one.
Now, something tells me that this self-cooked thing isn't the best one can do, mostly because I don't have an academic education and I tend to solve problems in stupid ways. What would you propose as a better alternative my method, where better is defined as stylistically better and/or more powerful?
(1) UPDATE 2019: ES7 Version
class Singleton {
static instance;
constructor() {
if (instance) {
return instance;
}
this.instance = this;
}
foo() {
// ...
}
}
console.log(new Singleton() === new Singleton());
(2) ES6 Version
class Singleton {
constructor() {
const instance = this.constructor.instance;
if (instance) {
return instance;
}
this.constructor.instance = this;
}
foo() {
// ...
}
}
console.log(new Singleton() === new Singleton());
Best solution found:
http://code.google.com/p/jslibs/wiki/JavascriptTips#Singleton_pattern
function MySingletonClass () {
if (arguments.callee._singletonInstance) {
return arguments.callee._singletonInstance;
}
arguments.callee._singletonInstance = this;
this.Foo = function () {
// ...
};
}
var a = new MySingletonClass();
var b = MySingletonClass();
console.log( a === b ); // prints: true
For those who want the strict version:
(function (global) {
"use strict";
var MySingletonClass = function () {
if (MySingletonClass.prototype._singletonInstance) {
return MySingletonClass.prototype._singletonInstance;
}
MySingletonClass.prototype._singletonInstance = this;
this.Foo = function() {
// ...
};
};
var a = new MySingletonClass();
var b = MySingletonClass();
global.result = a === b;
} (window));
console.log(result);
Why use a constructor and prototyping for a single object?
The above is equivalent to:
var earth= {
someMethod: function () {
if (console && console.log)
console.log('some method');
}
};
privateFunction1();
privateFunction2();
return {
Person: Constructors.Person,
PlanetEarth: earth
};
Extending the above post by Tom, if you need a class type declaration and access the singleton instance using a variable, the code below might be of help. I like this notation as the code is little self guiding.
function SingletonClass(){
if ( arguments.callee.instance )
return arguments.callee.instance;
arguments.callee.instance = this;
}
SingletonClass.getInstance = function() {
var singletonClass = new SingletonClass();
return singletonClass;
};
To access the singleton, you would
var singleTon = SingletonClass.getInstance();

Categories

Resources