How can i call AnotherSubFunction using my obj - javascript

var obj = {
MainFunction: function() {
AnotherSubFunction: function() {
}
var variable = AnotherSubFunction ()
}
}
Can i do something like this...
How can i call AnotherSubFunction using my obj? Is it possible.
How to create a function inside another function...

The code in your question is not valid Javascript. You're probably looking for:
MainFunction: function() {
function AnotherSubFunction() {
// ...
}
var variable = AnotherSubFunction();
}
Or maybe:
MainFunction: function() {
AnotherSubFunction = function() {
// ...
}
var variable = AnotherSubFunction();
}
However, in both cases, the name AnotherSubFunction associated with the nested function only exists in the scope of the enclosing function (MainFunction) and will not be accessible directly from obj.

Related

Javascript calling other object method

I have these two objects: A and B. I want to call A.something from B, but is not working...
A = function()
{
function something()
{
//do something
}
}
B = function()
{
A.something();
}
this throws "typeError, A.something(); is not a function"...
Your current code attempts to use A as an object when it is a function. You would need to invoke the function A(), but then its something method would still not be available (because it is not exposed).
If you want A to be an object, you could use an object literal like this:
A = {
something: function()
{
//do something
}
}
B = function()
{
A.something();
}
Or for a more classical looking approach you could use new:
function A()
{
this.something()
{
//do something
}
}
B = function()
{
var a = new A();
a.something();
}
There are more ways as well. You can use Object.create or use a more functional approach by returning an object inside the A function.
Don't declare A as a function itself, declare it as an object:
A = {}
Then inside place something as your function:
A = {
something: function() {
//do something
}
}
You will now be able to call A.something().
First of all, to create an object in javascript you have to define your class A like this (easy approach, not using prototyping):
A = function()
{
return {
something = function()
{
//do something
}
}
}
Then create your object by calling var object = A().
So your code should look like this in the end:
A = function()
{
return {
something = function()
{
//do something
}
}
}
B = function()
{
var aObject = A();
aObject.something();
}

private method in an javascript object

I've an object looks like this:
var obj ={
property : '',
myfunction1 : function(parameter){
//do stuff here
}
}
I need to set some private properties and functions, which can not be accessed/seen from outside of the object. It is not working with
var property:, or var myFunction1
Next question is, if I call a function within or outside the object, I always have to do this with obj.myfunction(). I would like to asign "this" to a variable. Like self : this. and call inside the object my functions and variables with self.property and self.myfunction.
How? :)
There are many ways to do this. In short: If dou define a function inside another function, your inner function will be private, as long as you will not provide any reference to if.
(function obj(){
var privateMethod = function() {};
var publicMethod = function() {
privateMethod();
...
};
return {
pubMethod: publicMethod
}
}());
var obj = (function() {
var privateProperty;
var privateFunction = function(value) {
if (value === void 0) {
return privateProperty;
} else {
privateProperty = value;
}
};
var publicMethod = function(value) {
return privateFunction(value);
}
return {
getPrivateProperty: function() {
return privateFunction();
},
setPrivateProperty: function(value) {
privateFunction(value);
}
}
})();
obj.setPrivateProperty(3);
console.log(obj.getPrivateProperty());
// => 3
console.log(obj.privateProperty);
// => undefined
obj.privateFunction();
// => TypeError: undefined is not a function
Use closures. JavaScript has function scope, so you have to use a function.
var obj = function () {
var privateVariable = "test";
function privateFunction() {
return privateVariable;
}
return {
publicFunction: function() { return privateFunction(); }
};
}();

Add function to object

I have the following code
var PROMO = PROMO || {};
PROMO.Base = (function () {
var _self = this;
var Init = function () {
WireEvents();
};
var WireEvents = function () {
//wire up events
};
} ());
In the same file I have the code to call the above function
I am trying to get to an end point where I can use the following code
$(document).ready(function () {
PROMO.Base.Init();
});
this gives the error
Cannot call method 'Init' of undefined
Now I know there are many ways to write javascript, but in this case I want to be able to call my functions, or least the Init method in the way shown above.
var PROMO = PROMO || {};
PROMO.Base = (function () {
var _self = this;
var Init = function () {
WireEvents();
};
var WireEvents = function () {
//wire up events
};
var reveal = {
Init: Init
};
return reveal;
} ());
You need to return the public facing functions. See updated code.
Working fiddle with both patterns, using IIFE and direct attribution.
Using var makes the definition private and your function is returning nothing. Use this:
PROMO.Base = {
Init: function() {
},
WireEvents: function() {
};
};
You are wrapping the definition with an IIFE(Immediately Executed Function Expression). So your PROMO.Base object will be assigned the value of that (function(){//blabla})(); returns. But your function doesn't have a return statement. By default it will return undefined.
Which is way your PROMO.Base will be undefined and you get this:
Cannot call method 'Init' of undefined
If you really want that IIFE:
var PROMO = PROMO || {};
// NEVER use _self = this inside static functions, it's very dangerous.
// Can also be very misleading, since the this object doesn't point to the same reference.
// It can be easily changed with Function.prototype.call and Function.prototype.apply
PROMO.Base = (function () {
_PROMO = {
Init : function () {
document.body.innerHTML += "itworks";
},
WireEvents : function () {
//wire up events
}
}
return _PROMO;
} ());
PROMO.Base.Init();
Update
The better and easier pattern is to simply assign the functions to PROMO.Base. Dully note you should not capitalize static functions, but only constructors. So if something is not meant to be instantiated, don't call it Init, it should be init. That is the convention.
var PROMO = {};
PROMO.Base = {};
PROMO.Base.init = function() {
console.log("this works");
};
PROMO.Base.wireEvents = function() {
console.log("this is a static function too");
};
You can attach it to the window object like ...
window.PROMO = (function($, _){
// this will access PROMO.Base
PROMO.Base = {
// inner functions here
Init:{}
};
})(jQuery, _);
Then load it as you do.
Or if you depend from jQuery
(function($){
var PROMO = {
// inner functions
Init: function(){},
WireEvents: function(){}
};
$.PROMO = PROMO;
})(jQuery);
On DOM ready
jQuery(function ($) {
var promo = $.PROMO || undefined;
promo.Base.Init();
});

Javascript "this" scope

I am writing some JavaScript code. I am a little confused about this keyword. How do I access logger variable in the dataReceivedHandler function?
MyClass: {
logger: null,
init: function() {
logger = LogFactory.getLogger();
},
loadData: function() {
var dataReceivedHandler = function() {
// how to access the logger variable here?
}
// more stuff
}
};
You can do something like this inside the loadData function to access your object...
MyClass: {
logger: null,
init: function() {
this.logger = LogFactory.getLogger();
},
loadData: function() {
var self = this;
var dataReceivedHandler = function() {
// how to access the logger variable here?
self.logger.log('something');
}
// more stuff
}
};
Assuming loadData is called like so:
MyClass.loadData();
then:
loadData: function() {
var self = this;
var dataReceivedHandler = function() {
self.logger ...
}
// more stuff
}
Because dataReceivedHandler is an anonymous function this will refer to the window object on the global scope. I think of two way you can bypass that.
a) Create a variable inside loadData to hold it's context then use it inside dataReceivedHandler as such:
loadData: function() {
var self = this;
var dataReceivedHandler = function() {
console.log(self.logger);
}
// more stuff
}
b) Change the context of your anonymous function using apply or call.
loadData: function() {
var dataReceivedHandler = function() {
console.log(this.logger);
}
// more stuff
dataReceivedHandler.call(this); // by passing this as the first argument we make sure the context of the excuted function is our current scope's this
}
I prefer option B due to performance and memory usage optimizations, but both would work just fine.

How to call a function placed in another function with jQuery, without modifying the original code?

This is basically the framework of my code:
var firstfunction = function () {
function innerfunction () {
// Do stuff here
}
}
How do I reference innerfunction(), without changing the code mentioned supra?
If you want to expose innerFunction as an API you could do the following:
var firstFunction = function () {
var imPrivate = "foo"
var innerFunction = function () {
// do stuff
}
return {
innerFunction : innerFunction
}
}
firstFunction.innerFunction()
This would also let you create private methods, variables as well.
It seems that you're wanting to make use of currying, this is a functional programming technique where you return an function from another function i.e.:
var f1 = function() {
return function() {
}
}
> f1()();

Categories