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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With