Check if a private function exists inside an object in JavaScript - 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.

Related

Converting code to ES6 modules

I have just started learning es6 module system. I have some es5 javascript code which I want to transform to es6 modules. There are 3 javascript files
workflow-designer.js
var WorkflowDesigner = (function () {
var constructor = function (element, options) {
var component = this;
if ($(element).hasClass('panel')) {
component.panel = $(element);
} else {
component.panel = $(element).closest('.panel');
}
};
extend(Object, constructor, {
getWorkflowName: function () {
return 'WorkflowName001';
},
nextStep: function () {
var o = {};
o['id'] = -1;
//some code here
return o;
},
prevStep: function () {
var o = {};
o['id'] = -1;
//some code here
return o;
}
});
return constructor;
})();
(function ($) {
$.fn.createWorkflowDesigner = function (options) {
debugger;
return this.map(function (index, element) {
return new WorkflowDesigner($(element), options);
});
};
}(jQuery));
extend.js
function extend(parent, child, methods) {
debugger;
let Surrogate = function () {};
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
child.prototype.constructor = child;
// Add a reference to the parent's constructor
child.parentConstructor = parent;
// Copy the methods passed in to the prototype
for (let name in methods) {
if (methods.hasOwnProperty(name)) {
child.prototype[name] = methods[name];
}
}
// so we can define the constructor inline
return child;
}
There a third file utils.js which contain extension methods like
if (!Array.prototype.find) {
Array.prototype.find = function (predicate) {
//some code here
}
}
if (!Array.prototype.doSomething) {
Array.prototype.doSomething = function (predicate) {
//some code here
}
}
$(document).keyup(function (event) {
//somthing here.
});
I know that to convert the code to es6 modules, I can simply export the extend function like export function extend(.....) in the extend.js file. However, I am not 100% sure how to convert the workflow-designer and utils.js to es6 modules.
I suspect that I need to something like below to convert my workflow-designer.js to es6 module:
export default function workflowDesigner() {
let constructor = function (element, options) {
options = options || {};
let component = this;
if ($(element).hasClass('panel')) {
component.panel = $(element);
} else {
component.panel = $(element).closest('.panel');
}
};
//rest of the code here....
return constructor;
};
Please let me know if I am moving into the right direction or not.
UPDATE:
As per #Bergi's suggesion I changed the extend function like below:
export default function extend(parent, child, methods) {
child.prototype = Object.create(parent.prototype);
child.prototype.constructor = child;
// Add a reference to the parent's constructor
child.parentConstructor = parent;
// Copy the methods passed in to the prototype
Object.assign(child, methods);
// so we can define the constructor inline
return child;
}
However, now I am getting error message that "workflowDesigner.getWorkflowName is not a function"
In the debug mode I can see that this function is available at workflowDesigner.__proto__.constructor.getWorkflowName. With the old code it works fine.
Just drop the IIFE from your module pattern - ES6 modules come with their own scope.
import extend from './extend.js';
export default function WorkflowDesigner(element, options) {
if ($(element).hasClass('panel')) {
this.panel = $(element);
} else {
this.panel = $(element).closest('.panel');
}
}
extend(Object, WorkflowDesigner, {
getWorkflowName: () => 'WorkflowName001',
…
});
const $ = jQuery; // you might want to solve this with a proper `import`
$.fn.createWorkflowDesigner = function (options) {
debugger;
return this.map(function (index, element) {
return new WorkflowDesigner($(element), options);
});
};

JavaScript function after object is created

I have a context function type that is defined as below:
var Context = function () {
this.run = function () {
method1();
method2();
}
var method1 = function () {
}
}
As it is clear in the definition, method2 is not defined in the context. I need every instance of Context passes its implementation of this method.
var c = new Context();
// This does not work! because the call in run() function
// is not this.method2();
c.method2 = function () {
alert("injected method2");
};
c.run();
I need to keep method2() in run without use of this object i.e. this.method2();
Any solution?
If you can define method2 before creating Context it will work no problem:
function method2() {
alert(2);
}
var c = new Context();
c.run();
You can add method2 to the window object instead of the c object, in which case it will work.
Note that this is a clear indicator of poor design. You should probably look into doing this differently.
Callback approach:
var Context = function (callback) {
this.run = function () {
method1();
if(callback) callback();
}
var method1 = function () {
}
}
var c = new Context(function () {
alert("injected method2");
});
c.run();
If you change your run method to the following it should work as expected
this.run = function () {
method1();
this.method2();
}
UPDATE: I just realized it looks like you want to be able to do this on all instances of Context objects. In that case you would also need to define method2 on Context.prototype and not just on c
Context.prototype.method2 = function () {
console.log("injected method2dfd");
};

Is it more efficient to use a common empty function instead of creating a new one in each class instance?

Let's say I have a class that is designed to have some callbacks added to it later on.
function myclass() {
this.onSomething = function () {};
this.onOtherThing = function () {};
this.something = function () {
// stuff
this.onSomething();
};
this.otherThing = function () {
// other stuff
this.onOtherThing();
};
}
I can't have this.onSomething and this.onOtherThing being undefined or null because when they are called in something() and otherThing(), an error will be thrown, stating that their type is not a function.
Since those empty functions are needed, but they use memory, is the class going to be more memory efficient if I did this?
function myclass() {
this.onSomething = empty;
this.onOtherThing = empty;
...
}
function empty() {
}
This way each class instance's properties point to the same empty function, instead of creating new functions every time. I assume defining an empty method doesn't take a lot of memory, but still... is this technically better?
You are right about the fact that a new function is created for every instance of your class. In order to have this shared across all instances you can declare it on the prototype of the class:
var MyClass = function() {
this.something = function () {
// stuff
this.onSomething();
};
this.otherThing = function () {
// other stuff
this.onOtherThing();
};
}
MyClass.prototype.onSomething = function() {};
MyClass.prototype.onOtherThing = function() {};
This way, the methods will be shared by all instances.
why don't you try to return true or return false instead of returning empty functions.
or best you can use :
function myclass() {
this.onSomething = false;
this.onOtherThing = false;
...
}
as per your comment you can try :
function myclass() {
this.onSomething = empty();
this.onOtherThing = empty();
... }
function empty() {
//return something
return true;
}

scope of "this" in async function of ionic angular app

I'm trying to execute a function, which is not found, UNLESS I save a reference to the function in a seperate variable:
function updateCheck() {
if (this.isNewVersionNeeded()) {
var buildFunc = this.buildObject();
this.updateBiography().then(function(){
buildFunc();
})
}
};
The buildObject function only executes if I save it before executing this.updateBiography (async function) and execute it via the variable I saved it in (buildFunc).
The following does NOT work:
function updateCheck() {
if (this.isNewVersionNeeded()) {
this.updateBiography().then(function(){
this.buildObject();
})
}
};
I expose all functions via a service object:
var service = {
all: all,
updateBiography: updateBiography,
get: get,
updateCheck: updateCheck,
isNewVersionNeeded:isNewVersionNeeded,
buildObject:buildObject
};
return service;
When I log the "this" object while Im right before the execution of buildFunc, it logs window/global scope. Why is this and how should I deal with this? I do not want to save all my async methods in a seperate variable only to remember them. How should I deal with this problem and why does it not work?
The entire service:
(function () {
angular
.module('biography.services', [])
.factory('Biography', Biography);
Biography.$inject = ['$http'];
function Biography($http) {
var biographyObject = { } ;
var service = {
all: all,
updateBiography: updateBiography,
get: get,
updateCheck: updateCheck,
isNewVersionNeeded:isNewVersionNeeded,
buildObject:buildObject
};
return service;
var self = this;
function updateCheck() {
if (this.isNewVersionNeeded()) {
this.updateBiography().then(function(){
self.buildObject();
})
}
};
function updateBiography() {
return $http.get("Apicall adress")
.then(function (resp) {
window.localStorage.setItem('biography', resp.data);
window.localStorage.setItem('biographyTimeStamp', Date.now());
}, function (err) {
console.log('ERR', err);
});
}
function all() {
return biographyObject;
}
function get(name) {
var biography = biographyObject;
for (var i = 0; i < biography.length; i++) {
if (biography[i].name === name) {
return biography[i];
}
}
return null;
}
function buildObject() {
var temp = JSON.parse(window.localStorage.getItem('biography'));
biographyObject = temp;
};
function isNewVersionNeeded() {
prevTimeStamp = window.localStorage.getItem('biographyTimeStamp');
var timeDifference = (Date.now() - prevTimeStamp);
timeDifference = 700000;
if (timeDifference < 600000) {
return false;
}
else {
return true;
}
}
}
})();
The context (different from function scope) of your anonymous function's this is determined when it's invoked, at a later time.
The simple rule is - whatever is to the left of the dot eg myObj.doSomething() allows doSomething to access myObj as this.
function updateCheck() {
if (this.isNewVersionNeeded()) {
this.updateBiography().then(function() {
// whichever object has this anonymous function defined/invoked on it will become "this"
this.buildObject();
})
}
};
Since you're just passing your function reference, you can just use this
function updateCheck() {
if (this.isNewVersionNeeded()) {
this.updateBiography().then(this.buildObject);
}
};
and if this.buildObject is dependent on the context (uses the this keyword internally), then you can use
function updateCheck() {
if (this.isNewVersionNeeded()) {
this.updateBiography().then(this.buildObject.bind(this));
}
};
this is determined by whatever context (object) the function is invoked on, and it appears that an anonymous function, or a function not referenced through an object defaults to having a window context. the bind function replaces all instances of this with an actual object reference, so it's no longer multi-purpose
same function invoked in different contexts (on different objects)
var obj = {
a: function () {
console.log(this);
}
};
var aReference = obj.a;
aReference(); // logs window, because it's the default "this"
obj.a(); // logs obj
The reason is here 'this' refers to callback function.You can't access 'this' inside callback.Hence solution is,
function Biography($http) {
var self = this;
function updateCheck() {
if (this.isNewVersionNeeded()) {
this.updateBiography().then(function(){
self.buildObject();
})
}
};
Using ES6 syntax:
function updateCheck() {
if (this.isNewVersionNeeded()) {
this.updateBiography().then(()=>{
this.buildObject();
})
}
};

Best approach avoid naming conflicts for javascript functions in separate .js files?

Is there a preferred approach to isolating functions in a .js file from potential conflicts with other .js files on a page due to similar names?
For example if you have a function
function AddTag(){}
in Core.js and then there is a
function AddTag(){}
in Orders.js they would conflict. How would you best structure your .js files and what naming conventions would you use to isolate them?
Thanks
I limit the scope of the function to that file.
(function () {
var AddTag = function AddTag () {
};
}());
… and sometimes make some functions in it available to the global scope:
var thisNamespace = function () {
var AddTag = function AddTag () {
…
};
var foo = function foo() {
AddTag();
…
};
var bar = function bar() {
…
};
return {
foo: foo,
bar: bar
}
}();
You can use 'namespacing'. Like this
File1.js:
var Orders = {}
(function(o) {
o.function1 = function() {}
o.function2 = function() {}
})(Orders);
File2.js
var Sales = {}
(function(o) {
o.function1 = function() {}
o.function2 = function() {}
})(Sales);
You can invoke them like this:
Sales.function1();
Orders.function1();
In general do not use global functions/variables. Read about javascript module pattern here http://yuiblog.com/blog/2007/06/12/module-pattern/
use encapsulation (http://www.devx.com/gethelpon/10MinuteSolution/16467 and http://nefariousdesigns.co.uk/archive/2006/05/object-oriented-javascript/)
in fileA.js
function fileA()
{
this.function1 = function()
{
return 'foo';
};
}
in fileB.js
function fileB()
{
this.function1 = function()
{
return 'bar';
};
}

Categories

Resources