Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object with Default function and other functions

Tags:

javascript

I am trying to create my own plugin for something, however, having trouble with the first step. I would like to have a an object that can take a parameter as default and have other functions in there as well. Please look at the example below on what I am trying to accomplish.

var a = function(str) { console.info(str); }
a = {
    Test: function() { console.info(TestMessage()); },
    TestMessage: function() { return "Test Message"; }
}

Basically, I want the parent object that I can call by itself with a parameter. a("test"); At the same time, I want other functions inside that parent object that can ALSO access other functions within that object. a.Test() -> calls a.TestMessage(), however, not having to write "a." every time while being inside that object.

like image 267
FerX32 Avatar asked Feb 11 '17 15:02

FerX32


1 Answers

The problem with your code is you're overwriting the value of a with the second statement. If you want to add properties to the function a refers to, you can do that by assigning to properties on it:

var a = function(str) { console.info(str); };
a.Test = function() { console.info(TestMessage()); };
a.TestMessage = function() { return "Test Message"; };

Now, instead of replacing the function reference in a with a reference to a new object, we're just adding properties to the function object it already refers to.

Note, though, that within Test, you need to qualify TestMessage in order to refer to it correctly:

a.Test = function() { console.info(a.TestMessage()); };
// --------------------------------^^

or if you can rely on a.Test always being called via a, then:

a.Test = function() { console.info(this.TestMessage()); };
// --------------------------------^^^^^

...but the former is more reliable.

Live Example:

var a = function(str) { console.info(str); };
a.Test = function() { console.info(a.TestMessage()); };
a.TestMessage = function() { return "Test Message"; };

a("Direct");
a.Test();
like image 160
T.J. Crowder Avatar answered Oct 01 '22 16:10

T.J. Crowder