how do I make a function including a dot - javascript

I want to make a function called "lib.hello" is that valid syntax and if not how do I do it?
here us my code function lib.hello(){ console.log("hello") }
function lib.hello(){
console.log("hello")
}

You can do it this way
function yourClass() {
}
yourClass.prototype.dotFunction = function() { return 'hello'; };
console.log(new yourClass().dotFunction());

first you must create an object next you do it same as bellow.
let Obj = {
a:1,
childMethod:(param)=>{console.log(param)}
}
Obj.childMethod("test")
Or you can do it by bellow code:
function yourClass() {
}
yourClass.prototype.childMethod = function(parameter) { console.log(parameter); };
var a = new yourClass();
a.childMethod("test");
//or you can do it same as follow
new yourClass().childMethod("test2")

Why are you asking to do this? This seems like either an XY Problem, or an exercise in theory.
As other answers have alluded to, you can make a class named lib with a method named hello, but that's not quite the same as a function named lib.hello.
Here's another variation:
let a = {
'lib.hello' : function() {
console.log('hello');
}
}
a['lib.hello']()
Technically this is an anonymous function, not a function named lib.hello, but it's kind of what you're asking for because it's associated with the key lib.hello.

Related

JS closure to return object instance as interface

I have the following code.
function Test() {
this.funct_1 = function() {
alert('funct_1');
}
this.funct_2 = function() {
alert('funct_2');
}
return this;}
function getTestObj() {
var testObj;
if (!testObj) {
testObj = new Test();
}
return function() {
return testObj;
}}
What I'm trying to accomplish is the following. I want to have a class Test which is not singleton. Then in some other places in my application I need to have a function which could return the same instance per script execution. I figured that I could use closure for that getTestObj.
However, when I try to use it
getTestObj().funct_1();
I'm getting the following error, saying the funct_1() is not found.
Cannot find function funct_1 in object function () {...}.
Clearly, I'm making some kind of mistake here, but I'm not able to find any solution over the net which could help me. Would appreciate any comments.
NOTE: I'm forced to use ECMA5
testObj is wrapped inside a function
So, either call it
getTestObj()().funct_1(); //notice two ()()
Save the value of getTestObj() in a variable
var singleTon = getTestObj();
var testObj = singleTon();
testObj.funct_1();
Or, simply return testObj (in case singleTon isn't required)
function getTestObj()
{
var testObj;
if (!testObj) {
testObj = new Test();
}
return testObj;
}
And invoke it as
getTestObj().funct_1(); //notice single ()
getTestObj() is returning a function i.e. :
function() {
return testObj;
}
So you have to call it again getTestObj()(), this will return the Test's object and now you can access it's properties.
getTestObj()().funct_1();
OR
You can change your getTestObj function as :
function getTestObj() {
var testObj;
if (!testObj) {
testObj = new Test();
}
return (function() {
return testObj;
}());
}

How to wrap plain function into a constructor?

Is it possible to make a wrapper function MyFunction, which when called with new as in
instance = new MyFunction();
really returns the same object as if the callsite called SomeOtherFunction without new?
instance = SomeOtherFunction();
(I've looked at Proxy but doesn't look like they're supported in Chrome yet.)
Edit:
It turns out the callsite calls MyFunction like this:
var instance = Object.create(MyFunction.prototype);
MyFunction.apply(instance, [/* arguments */]);
// `instance` is supposed to be initialized here
I think this is what you are looking for? Note as Jan Dvorak mentioned, you can only return objects.
function SomeObject() {
return Construct();
}
function Construct() {
return { 'name' : 'yessirrreee' };
}
console.log(new SomeObject())
You can try something like this
function MyClass() {
}
var ob = new MyClass();
Edit after comments
I think this questions needs more context.
I suggest you read about higher order components, but until you've better clarified what exactly you're trying to accomplish, I cannot help you.
I really don't know what your code looks like, but here are some suggestions
either way. My guess nr2 is what you're looking for:
// 1
function MyFunction() {
this.__proto__ = SomeOtherFunction()
}
function SomeOtherFunction() {
return {
foo: function() {
return 'bar'
}
}
}
var fn = new MyFunction()
fn.foo()
// 2
function MyFunction() {}
MyFunction.prototype = SomeOtherFunction()
function SomeOtherFunction() {
return {
foo: function() {
return 'bar'
}
}
}
var fn = new MyFunction()
fn.foo()
// 3
function MyFunction() {}
MyFunction.prototype = SomeOtherFunction.prototype
function SomeOtherFunction() {
function Foo() {}
Foo.prototype.foo = function() {
return 'bar'
}
}
var fn = new MyFunction()
fn.foo()

JavaScript convention: How do you assign arguments to the parent scope

var problemtest = function () {
var parameters;
return function (parameters) {
parameters = parameters;
}
}
var mysolutiontest = function () {
var parameters;
return function (parametersIn) {
parameters = parametersIn;
}
}
This is more of a JavaScript convention question.
Usually I have code similar to that on top. A function take arguments and assigns it to parent scope. However, I cannot use it as in problemtest, as the parameters that are arguments hide the parameters from problemtest.
In OO Programming we can use this, but in JavaScript I cannot use this, so I usually implement a solution similar to mysolutiontest. However, I am not fully satisfied with this solution. Is there a better way of doing this?
If your functions need to share some properties, then assigning them to an object is an elegant and common pattern:
var object = {
property: ['item'],
methodOne: function() {
console.log(this.property);
},
methodTwo: function() {
console.log(this.property);
}
};
object.methodOne(); // ['item']
object.methodTwo(); // ['item']
For further information on how 'this' works within an object - http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/
I usually use _parameters as a convention. This stems from my Java past. This isn't isolated to your example or to Javascript. Any language that does not force you to qualify the variables of any enclosing scope would lead you to the same problem.
var mysolutiontest = function () {
var _parameters;
return function (parameters) {
_parameters = parameters;
}
}
I've also seen people use p_parameters to quality function argument names. This is not one of my favorites tho.
var mysolutiontest = function () {
var parameters;
return function (p_parameters) {
parameters = p_parameters;
}
}
My 2c.

javascript is it possible to use a string to call a object function

I have a generic function which can speak to multiple other functions in appropriate objects is it possible to use a string to call the appropriate function.
var string = "save";
var generic = (new function (string) {
string."alert()";
return this;
})
var save = (new function (string) {
this.alert = (function () {
alert("your document has been saved")
return this
})
return this
})
var notSaved = (new function (string) {
this.alert = (function () {
alert("your document has not been saved")
return this
})
return this
})
I am using it for a far more complex set up but here is an example. Is this possible?
Sure you can. Try something like this:
window[string].alert();
Looking at your code it's hard to tell what you're actually trying to achieve. Nonetheless, here are a few ideas that may be relevant.
First, let's make a couple of objects:
var rabbit = {
name: 'Peter',
hop: function () {
return this.name + ' hopped!'
},
jump: function () {
return this.name + ' jumped!'
}
}
var hairy_maclary = {
name: 'Hairy Maclary',
jump: function () {
return this.name + ' jumped over the fence!'
}
}
Now, you could define a function which invokes the hop method on whichever object is passed to it:
function hop(object) {
return object.hop()
}
hop(rabbit) // 'Peter hopped!'
I'm not sure why you'd do this rather than invoking hop directly, but perhaps you want to do extra stuff before or afterwards.
If you wanted to you could create a completely generic function which would invoke a given method on a given object:
function invokeMethod(object, method) {
object[method]()
}
invokeMethod(hairy_maclary, 'jump') // 'Hairy Maclary jumped over the fence!'
This is a really strange thing to want to do, though. Perhaps you could provide more of an idea of what you're actually trying to do, since your example code is rather odd.
You can enclose your functions within some object so you can access by passing name of the property using some variable (in this case named string), eg. like that:
var string = 'notSaved';
var funcs = {};
funcs.save = new function(){
this.alert = function(){
alert('called save.alert()');
};
return this;
};
funcs.notSaved = new function(){
this.alert = function(){
alert('called notSaved.alert()');
};
return this;
};
funcs[string].alert();
See working example on jsfiddle.
If your variables are global (they should not), they are also automatically enclosed within window object, so you can call them also like that: window[string].alert(). This will not work for non-global functions (in this case my solution seems to be the only one not using eval()).
eval("alert('test');");
You can call functions with eval. Even you can declare functions.
eval("function test(){ alert("test");}");
test();

Returning the method of a function

In the code below, I've got two objects declared, with one object inheriting the properties and functions of another.
I want to use the super variable to call the methods of the object I inherited from. When I trace out itemEditor, I can see the function and it's methods correctly. When I try to access the method of itemEditor, it returns undefined.
What am I doing wrong? Is there a better way to do this?
var myObject = {
itemEditor : function (vars) {
this.editItem = function () {
alert("Editing Item");
}
},
recurringItemEditor : function (vars) {
myObject .itemEditor.apply(this, [vars]);
this.prototype = myObject.itemEditor.prototype;
var super = myObject.itemEditor
this.editItem = function () {
console.log("fn.recurringItemEditor.editItem");
console.log(super);
console.log(super.editItem);
super.editItem.call(this);
}
}
Your code seems a little confused. On the one hand myObject.itemEditor is a constructor and therefore a function (myObject.itemEditor.apply(this, [vars])), and on the other you treat it like an object with a prototype (this.prototype = myObject.itemEditor.prototype;).
That's not even considering that super is a reserved keyword.
Your example may be simplifying something you are trying to do, but I don't see why you don't just use the usual prototype inheritance. That way you can still have a method in your local instance and call the prototype one within it if you want e.g.
recurringItemEditor : function (vars) {
this.prototype = new myObject.itemEditor(vars);
this.editItem = function () {
console.log("fn.recurringItemEditor.editItem");
console.log(this.prototype);
console.log(this.prototype.editItem);
this.prototype.editItem.call(this);
}
}
I used your advice and it works well now. In regards to treating it like a function and an object, myObject .itemEditor.apply(this, [vars]); was still required in order for the object to inherit the properties of itemEditor. I should have made that clear in the original code. If there's a better way to do this, let me know.
var myObject = {
itemEditor : function (vars) {
var myVars = vars + "foo";
this.editItem = function () {
alert(myVars);
}
},
recurringItemEditor : function (vars) {
myObject .itemEditor.apply(this, [vars]);
this.prototype = new myObject.itemEditor(vars);
this.editItem = function () {
console.log("fn.recurringItemEditor.editItem");
console.log(this.prototype);
console.log(this.prototype.editItem);
this.prototype.editItem.call(this);
}
}
}

Categories

Resources