Add parameter to function dynamically [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
// set Process
i18n.setProcess(function() {diFunctions.getI18n('http://localhost/service/i18n/page?lang=eng&group=staff') });
// Setter and getter
this.setProcess = function( opProcess ) { //here param opProcess is function with parameters see i18n.setProcess() line of code
if( opProcess == undefined)
throw "Process is undefined";
if( $.isFunction(opProcess) == false )
throw "Process is not a function"
process = opProcess;
};
this.getProcess = function() {
return process;
};
See how i18n.setProcess passes a function with param as a parameter to setProcess.
Now i what i want in SetProcess is function() {diFunctions.getI18n('http://localhost/service/i18n/page?lang=eng&group=staff',**id**) // id is added dynamically to the function itself which was passed as parameter to setProcess
Problem - I want to add id dynamically(defined in my class variable always accesible by id) on set process with addition to functions parameter(Url,etc,etc,id). Functions parameters can grow but the id should be added last as a parameter?
Tried quite a few solutions but didnot work out? Check here

This is what the arguments object is for..
function foo() {
var lastArg = arguments.length ? arguments[arguments.length - 1] : 'default';
return lastArg;
}
foo(); // "default"
foo(1); // 1
foo(1, 2); // 2
If you want to write a function similar to bind which only sticks arguments on the end then you could do
function appendArguments(fn) {
var slice = Array.prototype.slice.call.bind(Array.prototype.slice),
args = slice(arguments, 1);
return function () {
return fn.apply(this, slice(arguments).concat(args));
};
}
now
var bar = appendArguments(foo, 3);
bar(); // 3
bar(4, 5); // 3 (because it's calling `foo(4, 5, 3)`

Related

Can this If statement be written in one line? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Is there a one line way of doing a if statement that only fires once with a boolean?
var boolean;
if (!boolean) {
function doSomething();
boolean = true;
}
Something in the lines of this.
You could take the logical OR assignment ||= with a comma operator.
boolean ||= (doSomething(), true);
It does not make much sense to do it as one line since the code is clear the way you have it written (minus your syntax error), but it can be done
function test(myBool) {
function doSomething () { console.log('run'); }
myBool = myBool || doSomething() || true;
console.log(myBool);
}
test(false);
test(true);
or if doSomething returns a true boolean or truthy value
function test(myBool) {
function doSomething () { console.log('run'); return true; }
myBool = myBool || doSomething();
console.log(myBool);
}
test(false);
test(true);

Why return a function instead of just running that function again (recursion)? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
If I want to run my function again inside that same function when a certain condition is met, what's the difference between returning that function VS just calling that function again.
function myFunc(param) {
if (param === "3") {
return myFunc(param);
}
}
VS
function myFunc(param) {
if (param === "3") {
myFunc(param);
}
}
If you need to return a result, then you need to return the result of the inner call recursively. For example:
function fact(n) {
if (n === 0) return 1;
return n * fact(n - 1);
}
console.log(fact(5));
But if the recursive function accomplishes what it needs to only inside the function - it's all side-effects from inside - then there's no need to return:
function addSpans(container, n) {
const span = container.appendChild(document.createElement('span'));
span.textContent = n;
if (n >= 1) addSpans(span, n - 1);
}
addSpans(document.body, 3);
return myFunc() does three things: (1) execute the function myFunc(), (2) when 1 finishes, take the result value and assign it as the return value of the current function, and (3) terminate the current function.
Calling myFunc() only does (1). That is the difference.

Access this in prototype function after a callback [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I have following code :
function A() {
this.value = 'a_value';
}
A.prototype.getValue = function(){
console.log(this.value); // got undefined, expected 'a_value'
}
setTimeout(new A().getValue, 100);
why i get this.value as undefined.?
and how how do i access this.value?
EDIT : i am not allowed to change the setTimeout line (last line) of code.
Hint: have you tried console.log(this);?
You are only passing the getValue function to setTimeout, not its context. Something like this would work: setTimeout(function() {new A().getValue();},100); But without changing that last line, there's basically nothing you can do.
you can avoid using the this altogether and not having this kind of problems with the following technique :
var A = function () { // no new no this
var value = 'a_value';
var getValue = function(){
console.log(value);
};
return Object.freeze({
getValue ,
});
};
setTimeout(A().getValue, 100);
or write
var a = new A();
before, and then
setTimeout(a.getValue.bind(a), 100);

Patterns for dealing with variadic arguments in JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I usually do something like the following when dealing with variadic arguments in JavaScript:
var f = function() {
var args = Array.prototype.slice.call(arguments, 0);
// ...
return something;
};
But what about doing instead:
var f = function() {
return (function(self, args) {
// ...
return something;
}(this, Array.prototype.slice.call(arguments, 0)));
};
I couldn't readily find anything addressing the pattern above, so I decided to post it here. Before I start experimenting with it, I would like to know if there are any flaws or risks I could be missing when using the rather unusual patterns described above.
I have found the pattern to be slightly less readable than the first, but it lets me write longer one-liners without declaring variables so I am growing fond of it.
Object.defineProperty(RegExp, 'join', {
value: function() {
return (function(regexes, last) {
return RegExp(regexes.map(function(item) {
return item.source;
}).reduce(function(prev, next) {
return prev + next;
}), last.slice(last.lastIndexOf('/') + 1));
}(Array.prototype.slice.call(arguments, 0),
arguments[arguments.length - 1]+''));
}, enumerable: false
});

scope of javascript callback functions [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was wondering what is the scope of a passed in callback function in Javascript.
callback = function() {
alert('hello');
}
func1 = function() {
func2(callback);
}
func2 = function(callback) {
func3(callback);
}
func3 = function(callback) {
callback();
}
When I call func1() .. it seems as if this extra layer of function loses that reference to callback(). I can call callback() from within func2, but not func3. Can anyone please advise?
you should see your code written as
var callback;
var func1;
var func2;
var func3;
callback = function() {
alert('hello');
}
func1 = function() {
func2(callback);
}
func2 = function(callback) {
func3(callback);
}
func3 = function(callback) {
callback();
}
the func1 scope includes all variables callback, func2 and func3. since all functions are initialized using function expressions and not function declarations like
function callback() {alert('hello');}
calling func1 will alert hello only if it is called at the bottom of your snippet.
Hopefully I have explained some of this in this jsFiddle. Look over the comments in the JS. This was done in a hurry, so feel free to update/comment/question. Code is below if you'd like to put test it locally.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="test">
</div>
<script>
// We're going to name our /callback/ something else to help with
// the confusion of using /callback/ wording everywhere.
var showMessage = function(message) {
document.getElementById("test").innerHTML= message;
}
var tellMe = function(message) {
document.getElementById("test").innerHTML = message;
return "Oh yes we did!";
}
// here we'll have one called callback just to show the name callback isn't anything special
var callback = function(message) {
document.getElementById("test").innerHTML= message;
}
// doesn't show anything, because you're not passing in a call back.
// if we wanted this to work we would have a param called callbackTest and
// we's pass in a function to be called back.
func1 = function() {
func2(callbackTest("Hi from func1"));
}
// does show message because you're not calling a callback, you're calling a function directly. Which is what you were doing above, just that there happened to not be a function called callback
// see explination below why we don't see Hi from func2, but Hi from func1_5 instead
func1_5 = function() {
func2(callback("Hi from func1_5"));
}
// here we're actually accepting a callback function named showMessage and using that as our callback by assigning it to the callback parameter variable. (remember, callback is not a fancy statement or call or anything. It's just a commonly named variable for.... callbacks ;) )
func2 = function(callback) {
// what you're doing here is actually passing the result of calling the callback (showMessage) to func3, and not the function. So you're actually executing the callback (showMessage) with the "Hi from func2", which outputs that, but returns nothing. So you're not passing anything at all to func3.
func3(callback("Hi from func2"));
}
// so here we'll show the previous problem, but working to provide insight.
// we're passing in a different /callback/ called tellMe. This function actually returns a string.
func2_5 = function(callback) {
func3(callback("Hi from func2_5"));
}
// here you're actually passing in a function to this as a callback, which is actually the showMessage function we pass in below.
func3 = function(callback) {
// the thing is, the callback variable is now a string and not a function because we got the result of the passed in callback call from above.
// so this will show a string for callback ("Oh yes we did!")
document.getElementById("test").innerHTML = callback;
// and this won't show anything because callback is not a function in this scope
if (typeof(callback) !== "function") {
alert("callback isn't a function");
}else {
callback(("Hi from func3"));
}
}
func4 = function() {
if (typeof(callback) === "undefined" ) {
alert ("the callback variable was never defined")
} else {
callback(("Hi from func4"));
}
}
</script>
<button onclick="func1();">func1</button>
<button onclick="func1_5()">func1_5</button>
<button onclick="func2(showMessage);">func2</button>
<button onclick="func2_5(tellMe);">func2_5</button>
<button onclick="func3();">func3</button>
<button onclick="func4()">func4</button>
</body>
</html>

Categories