I have a simple code to call a value from another function and its not working :
function ABC() {
var ID = XYZ(id);
Logger.log(ID); //throws error not defined.
}
function XYZ(id) {
var id = "1234"
return id;
}
What I wan to do is capture the value of id from function XYZ and Logger.log it into function ABC. But this reflects error.
Still not sure what you are trying to do with your code. This code is an "Impure Function" which is not recommended in JavaScript. How much I understood your code, below are my suggestions:
First
function abc() {
var id = xyz();
Logger.log(id);
}
function xyz() {
// Add whatever logic you want here to return ID value
var id = "1234"
return id;
}
Second
function abc() {
// Pass any value as an argument based on your requirement
var results = xyz('', '', '');
Logger.log(results.id);
Logger.log(results.name);
Logger.log(results.number);
}
function xyz(id, name, number) {
// Add whatever logic you want here
var newId = id || "1234";
var newName = name || "Mask";
var newNumber = number || "1234567890";
return { id: newId, name: newName, number: newNumber };
}
Based on what suits your requirement, you can take help of these codes.
Here you go -
function ABC() {
var ID = XYZ();
Logger.log(ID); // No longer throws the error :)
}
function XYZ() {
var id = "1234"
return id;
}
You do not need two functions, here is a simple function that will return the ID passed in.
const ABC = (id) => {
return id;
}
let a = ABC(122443);
console.log(a) // output 122443
Related
The following code gives me the error "Cannot read property PERSON1 of null". If I comment out the line where I try to assign the dynamic variable and uncomment the alert line it pops up alerts with each successive person's name.
function fillInternalRepData() {
var internalRepList = null;
console.log("Querying Table for internal reps");
queryTable(//..blabla..//, "false", function (callbackResp) {
internalRepList = callbackResp;
// alert("TRIGGERED"); //WORKS
// alert(internalRepList.length); //WORKS
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
$scope.internalReps[repName].such = repName;
//alert(repName); //WORKS WHEN LINE ABOVE IS COMMENTED OUT
});
}); //get list of internal reps
I simply want to create/add to the $scope.internalReps object so that I can add stuff to it like $scope.internalReps.PERSON1.Name = "Whatever"; $scope.internalReps.PERSON1.Salary = 100000;
Try adding an empty object for the "internalReps" before your forEach loop. It doesn't look like you've declared the object yet, so it can't dynamically add to a null object.
$scope.internalReps = {};
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
$scope.internalReps[repName] = {};
$scope.internalReps[repName].such = repName;
//alert(repName);
});
var internalReps = {};
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
internalReps[repName] = { such: "" };
internalReps[repName].such = repName;
//alert(internalReps[repName].such);
});
That worked. Thanks for the help!
I've an object called 'sheet1'
var nr = 1;
function Sheet(title){
this.div = document.createElement('div');
this.div.dataset.sheetNr = nr;
this.div.dataset.sheetTitle = title;
document.getElementById("sheets").appendChild(this.div);
nr++;
}
Sheet.prototype = {
constructor: Sheet,
get : function(data){
return this.div.dataset.data;
}
}
var sheet1 = new Sheet("Title1");
now when I call the function
sheet1.get("sheetNr");
it returns 'undefined' !...how can I solve this problem?
// console.log(data); outputs sheetNr
but when I change my function like
Sheet.prototype = {
constructor: Sheet,
get : function(){
return this.div.dataset.sheetNr;
}
}
and then call
sheet1.get();
it returns the number of the sheet...1 in this case...
http://codepen.io/anon/pen/rOXZjq?editors=101
You don't have a data attribute defined on the div you are creating sot it doesn't exist as called. When you call this.div.dataset.sheetNr you are actually hitting a defined attribute. To use the variable data as an index you need to call:
this.div.dataset[data] instead.
I have a text input that I want to enable users to call functions from.
Essentially I want to tie strings to functions so that when a user types a certain 'command' prefaced with a backslash the corresponding function is called.
Right now for example's sake you can type /name, followed by a value and it will set name as a property of the user object with the value the user gives.
So how would I do this with 20 or so 'commands'?
http://jsfiddle.net/k7sHT/5/
jQuery:
$('#textCommand').on('keypress', function(e) {
if(e.keyCode==13) {
sendConsole();
}
});
var user = {};
var sendConsole = function() {
value = $('#textCommand').val();
if (value.substring(0,5) === "/name") {
user.name = value.substring(6,20);
alert(user.name);
} else {
$('body').append("<span>unknown command: "+value+"</span><br />")
$('#textCommand').val("");
}
}
HTML:
<input id="textCommand" type="text"><br/>
Store your functions in an object, so you can retrieve and call them by key:
// Store all functions here
var commands = {
name : function() {
console.log("Hello");
}
}
var sendConsole = function() {
value = $('#textCommand').val();
// Strip initial slash
if(value.substring(0,1) === '/') {
value = value.substring(1);
// If the function exists, invoke it
if(value in commands) {
commands[value](value);
}
}
}
http://jsfiddle.net/NJjNB/
Try something like this:
var userFunctions = {
run: function(input)
{
var parts = input.split(/\s+/);
var func = parts[0].substr(1);
var args = parts.slice(1);
this[func].call(this, args);
},
test: function(args)
{
alert(args.join(" "));
}
};
userFunctions.run("/test hello there"); // Alerts "hello there".
You can do:
if(window["functionName"])
{
window["functionName"](params);
}
I am calling this function, assigning the result to a variable in the callback and then logging the result, but I keep getting undefined.
var id;
test.getID(function(result) {
id=result;
});
console.log(id);
If I change it to the code below, then I can see the id logged.
var id;
test.getID(function(result) {
id=result;
console.log(id);
});
Do you know what I can do to be able to access the result of the getID function?
The getID function will need to invoke its parameter before you will see id change.
Since you do not provide its implementation, let's assume it's something like this. Pay close attention to the implementation of getID, it takes a function as the parameter, f, and then invokes it. This is when id will be set.
var id;
var test = {
getID: function(f){
var result = 666; //assume result comes from somewhere
f(result); //Note: this is where your function is getting invoked.
}
};
test.getID(function(result) {
id = result;
});
console.log(id); //prints 666
A closure would work for you as well:
var id,
test = {
getID: function (id) {
this.id = id;
},
id: -1
};
test.getID((function(result) {
id=result;
return id;
})(78));
console.log(id);
I have a json object retrieved from server in my $(document).ready(...); that has an string that I would like to resolve to a function also defined within $(document).ready(...); so, for example:
$(document).ready(function{
$.getJSON(/*blah*/,function(data){/*more blah*/});
function doAdd(left,right) {
return left+right;
}
function doSub(left,right) {
return left-right;
}
});
with json string:
{"doAdd":{"left":10,"right":20}}
One way I thought about was creating an associative array of the function before loading the json:
var assocArray=...;
assocArray['doAdd'] = doAdd;
assocArray['doSub'] = doSub;
Using eval or window[](); are no good as the function may not be called for some time, basically I want to link/resolve but not execute yet.
Change your JSON to
{method: "doAdd", parameters : {"left":10,"right":20}}
Then do
var method = eval(json.method);
// This doesn't call it. Just gets the pointer
Or (haven't tried this)
var method = this[json.method]
How about something like this?
$(function(){
// Function to be called at later date
var ressolvedFunc = null;
// Ajax call
$.getJSON(/*blah*/,function(data){
// Generate one function from another
ressolvedFunc = (function(data) {
var innerFunc;
var left = data.left;
var right = data.right;
// Detect action
for (action in data) {
if (action == "doAdd")
innerFunc = function() {
return left + right;
};
else
innerFunc = function() {
return left - right;
};
}
return innerFunc;
})(data);
});
});
The anonymous function returns fresh function, with the new values stored within the enclosure. This should allow you to call the function at later date with the data previously retrieved from the GET request.
Rich
try this:
var doX = (function() {
var
data = [],
getDo = function(action) {
for(var d in data) {
if (data[d][action]) {
return data[d];
}
}
return null;
};
return {
set: function(sdata) {
data.push(sdata);
},
doAdd: function() {
var add = getDo("doAdd");
if (!add)
return 0;
return add.doAdd.left + add.doAdd.right;
},
doSub: function() {
var sub = getDo("doSub");
if (!sub)
return 0;
return sub.doAdd.left + sub.doAdd.right;
}
};
})();
$(document).ready(function{
$.getJSON(/*blah*/,function(data){ doX.set(data); });
});