function example(str) {
var cache = ( str != "" ) ? str : null;
}
example("something");
alert(cache); // cache is not defined
On alert, it says cache is not defined. How to make it so that after calling a function, cache will be saved and I could invoke it like alert(cache).
The variable 'cache' is defined in the function example and not outside that scope so alert does not have access to it. Please look at other similar questions, example: https://stackoverflow.com/questions/22113894/variables-from-anonymous-function/22114051#22114051 ; not 10 minutes ago. I would also recommend reading on Javascript especially how variable scope works. It is very similar to most programming languages but funky in a couple other, ex: http://msdn.microsoft.com/en-us/library/bzt2dkta(v=vs.94).aspx
Not recommended, but a quick answer is:
var cache;
function example(str) {
cache = ( str != "" ) ? str : null;
}
example("something");
alert(cache);
cache is a local variable to example function. I suggest to use a namespace instead of a global variable. If it wont be a global variable, be free to use a classic var declaration.
so:
var app = app || {}; //define namespace
app.cache = "";
function example(str) {
app.cache = str != "" ? str : null;
//i guess it should equal to:
// cache = str ? str : null;
}
console.log(str); //similar to alert, but logs in developers tool (chrome) or firebug(FFx)
ps: I suggest the use of console.log() (or debug) instead of alert(). It's more comfortable than alert()
Self-memorizing functions
Memorization is the process of building a function that’s capable of
remembering its previously computed values. This can markedly increase
performance by avoiding needless complex computations that have
already been performed.
function foo(str) {
if (!foo.cache) {
foo.cache = ( typeof str !== undefined ) ? str : null;
}
}
foo("something");
alert(foo.cache);
Define cache outside function exmaple()
var cache;
function example(str) {
cache = ( str != "" ) ? str : null;
}
When you define inside the function it's scope would be finished inside it, so you can not access cache from outside of function in your case.
Related
I use this dom command in some testing pages:
document.querySelector('div#summary-item div.description').innerHTML || ""
But in some pages when the first part does not exist I don't receive the second "" but I receive this error and my programm stops
Uncaught TypeError: Cannot read property 'innerHTML' of null(…)
Is there any simple way to receive the "" without the need to use the typeof in an if statement?
You don't need typeof but you do need an if statement or some other flow control.
var el = document.querySelector('div#summary-item div.description');
var data = "";
if (el)
data = el.innerHTML;
Or here it is using the conditional operator:
var el = document.querySelector('div#summary-item div.description');
var data = el ? el.innerHTML : "";
Technically, you could get away without using a flow control statement or expression by using an object that has a .innerHTML property.
var data = (document.querySelector('div#summary-item div.description') || {innerHTML:""}).innerHTML;
But I think that's ugly. if statements are part of the language. Not sure why you'd want to avoid it.
Of course, you could always use a function that abstracts it away if it really bothers you.
function htmlFromElem(selector) {
var el = document.querySelector(selector);
return el ? el.innerHTML : "";
}
Then use it like this:
var data = htmlFromElem('div#summary-item div.description')
I guess I'm a beginner at javascript and as the title suggests, my function won't fully execute.
function showBorder2(classid){
var first2 = document.getElementById("swordsmanIcon");
var second2 = document.getElementById("marksmanIcon");
var third2 = document.getElementById("scribeIcon");
first2.style.borderColor = "transparent";
second2.style.borderColor = "transparent";
third2.style.borderColor = "transparent";
classid.style.borderColor = "Aqua";
alert("1");
var classType = elementid.id;
alert("2");
window.classType = classType;
}
I've ran a little test and i have discovered that alert 1 triggers, but alert 2 does not... This is probably a simple mistake but I really can't see it.
Thanks in advance!
if alert1 is triggering but not alert2, the problem must be that elementid is not defined and trying to access a property of an undefined variable will throw an error and break execution of your js. The solution:
a) make sure to define elementid
b) if you can't guarantee definition of elementid, add a check to see if it is defined before trying to access a child property.
A simple shorthand for this is var classType = elementid && elementid.id;
^ that's short for something like this:
var classType;
if(elementid) {
classType = elementid.id;
}
Probably one of your element variable (first2, second2, third2, classid) is either null or undefined. It is good defensive programming (especially in javascript) to check for null or undefined before using the variable.
I'm guessing when the showBorder2 function is called, the parameter passes to "classid" either is not a valid element or nothing is pass to it.
i have seen multiple questions of a similar nature on here, yet none would work for the specific thing that i have (im using node.js). so for example take this code here.
function command_call(message, socket) {
if (message.length > 1){
var func = message[0];
var string = message.slice(1);
var string = string.join(' ')}
else{
var func = message[0];
var string = '';};
if(func[0] == '$') {
(eval(func.slice(1)))(string, socket);};
};
function say(string, socket){
socket.write(string)};
if the message passed in to the command_call were to be "$say hi" the function say would be called and return "hi". this works just fine however, if the function that was put to the eval does not exist, it crashes. for instance if the message passed to the command_call were to be "$example blah" it would try to eval "example". basically i need it to check if the function exists before it evals the function. and YES i want to use eval, unless there is a better way to do it in node. and again, this is in node.js
You should make an object of functions and use indexer notation:
var methods = {
$say: function() { ... }
};
if (!methods.hasOwnProperty(func))
// uh oh
else
methods[func]();
I'm implementing Stoyan Stefanov's javascript namespace function as I have been reading his very informative JavaScript Patterns book; in my web application but not sure if I'm using it the proper way
here is the funciton implementation i'm using on my web app on this page http://dalydd.com/projects/module_example/
var COOP = COOP || {};
COOP.namespace = function (ns_string) {
var parts = ns_string.split('.'),
parent = COOP,
i;
// strip redundant leading global
if (parts[0] === "COOP") {
parts = parts.slice(1);
}
for (i = 0; i < parts.length; i += 1) {
// create a property if it doesn't exist
if (typeof parent[parts[i]] === "undefined") {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
};
COOP.namespace('sliderContainer')
COOP.sliderContainer = function () {
return slider = ($('#slider').length > 0) ? $('#slider') : $('#element_temp');
} // we need this at the beginning as others are dependent on it and call it initially
my goal is to check every new property of COOP to see if it exists before it's implemented --- so if I create a property of COOP called COOP.sliderContainer - I want to make sure COOP.sliderContainer does not exist already. when I use the namespace function it returns an object but COOP.sliderContainer is a function. I feel like I have to do an extra layer of abstraction in order to name this namespace function work properly like
var sliderContainer = COOP.namespace('sliderContainer');
sliderContainer.sliderContainer = function () {
return slider = ($('#slider').length > 0) ? $('#slider') : $('#element_temp');
}
this seems silly and redundant to me - is there a better way to do this?
any info is appreciated as always - the page has a direct link to the js file on it
namespace function is useful when create sub namespaces inside COOP, it will help to avoid multiple checkings. For example you want to create COOP.module.module1, you have to make 2 checks to see if module and module 1 are not defined or not.
However, in this case, sliderContainer is just a property of COOP. There's no need to use namespace. You just simply check it yourself:
if(COOP.sliderContainer === undefined){
// define it
}
EDIT
You can have a function handle that for you:
COOP.createProperty = function(name, prop){
if(COOP[name] === undefined){
COOP[name] = prop;
}
}
then
COOP.createProperty("sliderContainer", function(){
// do whatever you want
});
I only want my JavaScript to run once, but I cannot control how many times the javascript file is executed. Basically I'm writing a tiny JS snippet into a CMS, and the CMS is actually calling it 5-10 times. So solutions like this:
function never_called_again(args) {
// do some stuff
never_called_again = function (new_args) {
// do nothing
}
}
never_called_again();
Don't seem to work because as soon as my snippet is run again from the top the function is re-declared, and 'do some stuff' is re-evaluated. Perhaps I'm just not doing it properly, I'm not great with JS. I'm considering using something like try-catch on a global variable, something like
if (code_happened == undefined) {
\\ run code
code_happened = true;
}
EDIT: There is a consistent state e.g. if I set a variable I can see when my snippet is run again. But having to declare it before I access it, I don't know how to say 'does this variable exist yet'
Try this:
var doneTheStuff;
function whatever() {
if (!doneTheStuff) {
doneTheStuff = true;
// do the stuff
}
}
Redundant variable declarations don't affect the value of the variable. Once one of the functions has set the variable to true, the others won't do anything.
if (typeof code_happened === 'undefined') {
window.code_happened = true;
// Your code here.
}
The typeof check gets you around the fact that the global hasn't been declared. You could also just do if (!window.code_happened) since property access isn't banned for undefined properties.
Use a closure, and set a flag. If the flag is true, just return:
if ( ! window.never_called_again ) {
window.never_called_again = (function () {
var ran = false;
return function (args) {
if ( ran ) return;
ran = true;
// Do stuff
};
}());
}
Here's the fiddle: http://jsfiddle.net/U2NCs/
With jQuery, the function .one() may be useful : http://api.jquery.com/one/
W3School exemple here : http://www.w3schools.com/jquery/event_one.asp
In this way, the code is executed only once.
if(typeof onceRun == "undefined") window.onceRun=(
()=>{
//your codes...
console.log("runing...")
return true
}).call()