How do I chain call functions? - javascript

Hey guys am new to javascript app development
When i tried this code
function name() {
return 5;
}
function anotherone() {
return 3;
}
function horse() {
return 5;
}
When i called the function like console.log(name().anotherone().horse()); ..it throws me error like undefined not a function.
Is it possible to call function like afunction().anotherfunction().anotherfunction1() in javascript ??
Thanks in advance..

When you callname().another(), this evaluates to (5).anotherone().
anotherone() is not a function of the literal 5, which is why you get the error undefined is not a function. If you want to chain methods, use a class/object that returns an instance of itself so you can call myClass.aFunction().anotherfunction() so the call stack evaluates to (myClass).anotherfunction()

Yes it is. Every function but the last in the chain have to return the object containing the function you call next, for example:
var obj = {
foo: function(){ return obj; },
bar: function(){ return obj; },
baz: function(){ return 123; }
};
console.log(obj.foo().bar().baz()); // works, logs 123

Read more about OOP in javascript
var Class = function () {};
Class.prototype = {
value: 0,
addOne: function () {
// do stuff
this.value++;
return this;
},
addTwo: function () {
this.value = this.value + 2;
return this;
},
getValue: function () {
return this.value;
}
};
var obj = new Class();
// Chaining possible when you return the object at the end of your method
console.log(obj.addOne().addTwo().addOne().getValue()); // returns 4
// Chaining is not possible when you return something else
console.log(obj.addOne().getValue().addOne()); // undefined is not a function

The problem is your syntax.
Look at your functions: the first returns 5, so you're essentially doing 5.anotherone(). Dot notation is for accessing properties and methods of an object. anotherone() is not a method of 5, so you'll get undefined is not a function.
Also, you don't provide any arguments for the functions, so you can't pass anything to them.
You can kind of do what you're describing, but you have to go about it a bit differently:
function name() {
return 5;
}
function anotherone(num) {
return num + 3;
}
function horse(num) {
return num + 5;
}
console.log(horse(anotherone(name())));
Demo

Its quiet easy:-
function name() {
return 5;
setTimeout(anotherone,0);
}
function anotherone() {
return 3;
setTimeout(horse,0);
}
function horse() {
return 5;
}
Now you just need to call the first function and it will call the next one itself.

Related

How to Define a function to invoke like this: function1().function2()?

function1().function2();
How to Define a function to invoke like this?
In addition to the other answers, you usually would do this when coding a fluent interface, where you are returning the parent object to allow method chaining, which you could do like so:
var calculator = (function() {
var i = 0;
var public = {};
public.add = function(a) { i += a; return public; }
public.sub = function(a) { i -= a; return public; }
public.equals = function() { return i; }
return public;
})();
console.log(calculator.add(2).sub(3).add(20).equals());
here you have a working example, you can call function1 and get the object mapping to the functions that you desire.
function function1() {
return {
function2: f2
}
}
function f2() {
return "do something";
}
console.log(function1().function2())
You'll need function1 to return an object that has a property of function2. For example:
function f1() {
return {
f2() {
console.log('foo');
}
};
}
f1().f2();

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;
}());
}

Why do we use functionName: function in javascript return statement

I am completely new to javascript. I saw the below snippet in a tutorial. But i am not sure why do we use funtionName: function in return statement.
For example, getID:function() and setID: function() in the below code. Can anybody explain.
function celebrityID () {
var celebrityID = 999;
return {
getID: function () {
return celebrityID;
},
setID: function (theNewID) {
celebrityID = theNewID;
}
}
}
in your celebrityID () function you are returning an object, which has two properties those properties are function.
you can call
var myVar = new celebrityID();
myVar.getID(); // myVar = 999
this like object creation from a class
So they can use it as
var cid = celebrityID();
var celbId = cid.getID();
If you do not have the return statement the function getID() will not be useful and also celbId becomes undefined.
If you closely observe, there is no return statement for setter.

Why does object prototype methods have no caller in oop unlike in procedural programming

If I have a procedural function calling another procedural function like this:
function awesome() {
return arguments.callee.caller.name;
}
function ridiculous() {
return awesome();
}
ridiculous();
Then I get back the caller named "ridiculous". But when I write it in oop-style, then the caller is null.
function myObj() {}
myObj.prototype.awesome = function() {
return arguments.callee.caller.name;
}
myObj.prototype.ridiculous = function() {
return this.awesome();
}
I wonder, why this happens and how to get back the caller anyway.
The key in the object and the name of the function isn't the same thing.
Take a look at my snippet:
function myObj() {}
myObj.prototype.awesome = function awesome() {
return arguments.callee.caller.name;
}
myObj.prototype.ridiculous = function ridiculous() {
return this.awesome();
}
var o = new myObj();
console.log(o.ridiculous())
It's because when declaring methods on prototype you should be using named functions.
such as:
function myObj() {}
myObj.prototype.awesome = function awesome() {
return arguments.callee.caller.name;
}
myObj.prototype.ridiculous = function ridiculous() {
return this.awesome();
}
myObj.prototype.ridiculous()

Parameter of a function within a function

How must a function be 'chained', in order to call this function like this
F('Test').custom_substring(0,1);
You have to return an object that has a method member named custom_substring. One example:
var F = function(){
return {
custom_substring:function(){
console.log('custom substring');
return this;
}
}
}
F('Test')
.custom_substring(0,1)
.custom_substring(0,1)
.custom_substring(0,1);
To create objects you can use constructor functions and prototype, this is a complex subject and explained here.
I would not mess with the String.prototype because that breaks encapsulation.
The following sample provides a chainable custom_substring that does not modify the original object but instead returns a new one. This is similar to how jQuery and other libraries work (and how built-in string operations work) and it helps make for safer and more predictable code.
function F(str) {
return {
toString: function () { return str; },
// You didn't provide an example of what you want custom_substring
// to do, so I'll have it append a "!" to the beginning of the resulting value
// (since I can't think of anything else for it to do)
custom_substring: function (from, to) {
return F("!" + str.substring(from, to));
}
};
}
var s1 = F("Hello everyone");
var s2 = s1.custom_substring(0, 7);
var s3 = s2.custom_substring(0, 5)
.custom_substring(0, 4);
console.log(s1); // Hello everyone
console.log(s2); // !Hello e
console.log(s3); // !!!He
If you really want to create chainloading you need always return this from methods where it's possible.
For example we have some class with some methods:
function Foo() {
this.foo = 'bar';
return this;
}
Foo.prototype = Object.create({
sayFoo: function() {
console.log(this.foo);
return this;
},
getFoo: function() {
return this.foo; // Here you can't make chainload
},
saySmth: function() {
console.log('Something');
return this;
}
});
And we can use this:
var test = new Foo().sayFoo().saySmth().getFoo(); // prints this.foo -> 'Something' -> returns this.foo
console.log(test); // prints out this.foo

Categories

Resources