Send a variable to a variable of a function? - javascript

Let's say I have a function and one of the parameters is for the name of the target variable.. Would it be possible for me to send a variable to the function like this:
function otherfunction(input){
...
}
function test {target) {
var x = 1;
target(x);
}
test(otherfunction);
The problem I have is that I'm making a greasemonkey script and one of the variable I need can't be returned from the function due to a limitation.. So this would be the alternative. I just don't know how to get it to work.. Any help would be much appreciated!!

Your example (almost) works:
function otherfunction(input){
alert(input);
}
function test(target) {
if(typeof target !== 'function') {
alert('target is not a function!');
return;
}
target(1); //invokes the passed-in function, passing in 1
}
test(otherfunction); //alerts 1
//You can also do it with an anonymous function too:
test(function(arg) {
alert(arg * 5);
}); //alerts 5
jsFiddle example

Related

javascript - pass data from one function to another

I have two functions. I want this function:
function indentSpace(s, n){
return ((new Array(n+1)).join(s));
}
To get it's parameters from this function, while allowing this function to continue:
function onHandle(line, report) {
var input = $.trim(line);
if (parensBalanced(input) == false) {
indentSpace('.',input.length);
controller.continuedPrompt = true;
} else if (parensBalanced(input) == true) {
controller.continuedPrompt = false;
if (doCommand(input)) {
report();
return;
}
...
}
}
So that the 1st function gets used here, as the value for continuedPromptLabel:
$(document).ready(function() {
controller = $("#console").console({
continuedPromptLabel: indentSpace,
completeHandle: onComplete,
});
});
I've tried it several different ways, and it seems that once I get a value for indentSpace, it also returns that value in its containing function - and breaks other stuff.
Cheers!
So you want indentspace to essentially have a closure on its parameters from being called asynchronously from onHandle, such that onHandle is running freely, but then you want that indentspace with those parameters to be used elsewhere? I don't think that's possible.

Javascript: Combine function argument with string to reference var

I have vars that look like this:
var cardholder = $("#cardholder");
var cardholderInfo = $("#cardholder-Info");
And a function (which doesn't currently work) that looks like this:
function validateRequired(field){
//if it's NOT valid
if(field.val().length < 1){
field.addClass("field_error");
fieldInfo.text("(Required)");
fieldInfo.addClass("error");
return false;
}
//if it's valid
else{
field.removeClass("field_error");
fieldInfo.text("");
fieldInfo.removeClass("error");
return true;
}
}
Which I access like:
cardholder.keyup(validateRequired(cardholder));
I've looked everywhere but I can't find what I need and I'm not really sure what I should be searching for.
I can use the field value to access the straight cardholder var. But I also want to use the field value to then reference cardholderInfo so I can manipulate that element in the function.
You would call the function like this, passing the second parameter:
cardholder.keyup(function () {
validateRequired(this, cardholderInfo);
});
And modify your function to take a second parameter:
function validateRequired(field, fieldInfo){
/* validation stuff */
}
No need for the global variables:
function validateRequired($cardInfo){
// You can guess what $cardInfo is
//if it's NOT valid
if(this.val().length < 1){
this.addClass("field_error");
$cardInfo.text("(Required)");
$cardInfo.addClass("error");
return false;
}
//if it's valid
else{
this.removeClass("field_error");
$cardInfo.text("");
$cardInfo.removeClass("error");
return true;
}
}
$(document).ready(function(){
$("#cardholder").keyup(function(){
validateRequired.call($(this),$("#cardholder-Info"));
});
});
Don't call the function you want to bind! If you need to pass an argument to it every time it is called, you either need to use bind or a function expression:
cardholder.keyup(functio(e) {
return validateRequired(cardholder, cardholderInfo);
});
Also you will need a second parameter in your validateRequired function to get the fieldInfo variable filled:
function validateRequired(field, fieldInfo){
…
You have to pass reference of function in keyup, you do not have to call function
cardholder.keyup(function(){
validateRequired(cardholder)
});

Javascript Initialization Closure

I'm trying to create javascript closure that will tell me if the function has already been run:
This is what I have so far:
function do()
{
var isInitialized = function()
{
var init = false;
if (init == false)
{
init = true;
return false;
}
return init;
}
if (!isInitialized())
{
// do stuff
}
}
My function isInitialized always evaluates to true. I'm like 90% sure I'm not setting the internal variable correctly. How do I fix my code?
First of all, you can't use do as your function name as that's a keyword.
Secondly, you can attach properties right to your function so you don't need a closure or anything like this:
function f() {
if(f.initialized)
return;
f.initialized = true;
console.log('Doing things.');
}
f();
f();
That will give you just one "Doing things." in the console.
Demo (run with your JavaScript console open): http://jsfiddle.net/ambiguous/QK27D/
Functions are objects in JavaScript so they can be assigned properties which provides a convenient mechanism for achieving what you want to do:
function doit() {
if (typeof doit.isInitialized === "undefined") {
doit.isInitialized = true;
// do stuff
}
}
Try this:
function fn(){
if (typeof fn.hasrun!='undefined'){return;}
fn.hasrun=true;
// do stuff
}
Every time you call isinitialized, it'll reset all the variables to default, so init will ALWAYS start out false. The values set afterwards are NOT carried over to the next time isInitialiazed is called.
What you want is a 'static' variable, which JS doesn't directly support, but can be simulated as per this answer: Static variables in JavaScript

unexpected call to a function in Javascript

I'm not really good at javascript so I'm here asking.
Below is a sample code.
<html>
<head>
<script>
function test(one)
{
alert('surprise! first function with one parameter');
}
function test(one,two)
{
alert('expected: second function with two parameters');
}
</script>
</head>
<body onload="javascript:test('first')">
</body>
</html>
Questions:
I expected that that 'surprise! first function with one parameter' would be then alerted onload because I call the function with one parameter only. To my surprise it alerted in the second function.
Can someone explain this to me why?
and how can I make my way around it?
Javascript doesn't support method overloading;
It just overwrites the function so the last one will get called every time.
A way around it is just to make 1 function and put some conditions in there to check if the variables are set.
You declare twice the function test. The 2nd one overwrite the first definition.
In JavaScript overloaded functions are not allowed. so in this case the second function overrides the first one and therefore you always see this result.
A work around for this is to check the values of the parameters:
function test(one,two)
{
if(two)
alert('expected: second function with two parameters');
else
alert('surprise! first function with one parameter');
}
In javascript the parameters for a function aren't required. You'd want to check to see if the parameter is undefined before using it.
If used this before in order to implement getter/setter type functionality in javascript similar to below:
var _pageSize;
function pageSize(value) {
if (value) {
_pageSize = value;
}
else {
return _pageSize;
}
}
You can then use the pageSize method to both get and set the page size like below:
if (pageSize() < 15) {
pageSize(15)
}
Ah, Javascript doesn't do polymorphism like that. It does have an arguments collection that you can look in and then do the right thing given the inputs..
stuff like:
function calcAverage()
{
var sum = 0
for(var i=0; i<arguments.length; i++)
sum = sum + arguments[i]
var average = sum/arguments.length
return average
}
document.write("Average = " + calcAverage(400, 600, 83))
When calling such function:
function test(one,two)
With only one parameter, the argument "two" will have special type: undefined.
Any attempt to access the variable two will fail with "two is undefined" error, to avoid such error use the typeof command:
function test(one,two)
{
if (typeof two == "undefined") {
//give default value
two = "default value here";
}
...
}

How can I get the name of function inside a JavaScript function?

How is it possible to learn the name of function I am in?
The below code alerts 'Object'. But I need to know how to alert "Outer."
function Outer(){
alert(typeof this);
}
This will work:
function test() {
var z = arguments.callee.name;
console.log(z);
}
I think that you can do that :
var name = arguments.callee.toString();
For more information on this, take a look at this article.
function callTaker(a,b,c,d,e){
// arguments properties
console.log(arguments);
console.log(arguments.length);
console.log(arguments.callee);
console.log(arguments[1]);
// Function properties
console.log(callTaker.length);
console.log(callTaker.caller);
console.log(arguments.callee.caller);
console.log(arguments.callee.caller.caller);
console.log(callTaker.name);
console.log(callTaker.constructor);
}
function callMaker(){
callTaker("foo","bar",this,document);
}
function init(){
callMaker();
}
As of ES6, you can use Function.prototype.name. This has the added benefit of working with arrow functions, since they do not have their own arguments object.
function logFuncName() {
console.log(logFuncName.name);
}
const logFuncName2 = () => {
console.log(logFuncName2.name);
};
Took me a while to figure this out, so tried to make it very clear for rookies like me.
Approach 1 - arguments.callee.name
This approach used to work, but now in ES6 Strict Mode it will fail. Don't use Approach 1.
//approach 1 - don't use
let functionName = arguments.callee.name;
console.log(functionName);
Approach 2 - create a function and use caller.name
This approach works in the latest version of Javascript and will not fail in Strict Mode. Use Approach 2. There are 2 steps.
Step 1 - Create a function that uses caller.name to return the name of the function that called it. Add this function to your code:
function getFuncName() {
return getFuncName.caller.name
}
Step 2 - Call your function when you need the name of the function your code is currently in.
function iWantThisName() {
console.log(getFuncName())
}
iWantThisName()
// Logs: "iWantThisName"

Categories

Resources