Using Firebug and jsfiddle.net to test a function - javascript

Im a newbie programmer who got the function below from Stoyan Stefanovs object oriented JavaScript Book. He says that if you call next three times, it will output "a" and "b" and then "c". When I tried it in firebug console, it kept giving me "a", so that`s one question (a) i.e. is there something about firebug that would explain my result?
Next, I tried to run it in jsfiddle.net but it won`t output anything. http://jsfiddle.net/mjmitche/SkSMm/
Im sure Im doing something wrong, but what? Please explain if you can. Note, I did next(); and got A, and then I did next(); again and got 'a' and next(); again and got 'a'. In other words, the counter didnt change or didnt remember.
function setup(x) {
var i = 0;
return function () {
return x[i++];
};
}
var next = setup(['a','b','c']);
next();

Here is the jsfiddle link to show it works:
http://jsfiddle.net/ZnZTk/

JsFiddle is not like the console, it doesn't have a window where it will output return values. The result of the code is a web page, that is shown at the lower right.
You can use the alert method to show the values:
alert(next());
http://jsfiddle.net/SkSMm/4/
As you see, calling next three times will actually output the three values in the array. The setup function returns a delegate to the anonumous function that is created in the function. As that anonymous function uses variables outside itself, but which are local to the surrounding function, a closure is created for the function. The closure will contain the i and x variables. As the closure belongs to the delegate, it will survive from one function call to the next, and retain the values of it's variables.
You could do a similar thing just using global variables:
var x = ['a','b','c'];
var i = 0;
function next() {
return x[i++];
}
alert(next());
alert(next());
alert(next());
As the variables are declared outside the function, they will survive between the function calls.
The drawback of using global variables is that one script easily clashes with another if the variables are not given very unique names. If you use a closure, there is no risk of the variables of one script to conflict with variables of another script.

You did it wrong:
And jsfiddle: http://jsfiddle.net/ZHgW2/

Here's a neat demo that takes advantage of an imported say function and relies on a button:
http://jsfiddle.net/entropo/wxTqR/
This is a great way to test your scripts without relying on the log or alerts.
The say function is from jQuery in Action. Excerpt:
Within this function, we employ the services of a small utility function, say() C,
that we use to emit text messages to a dynamically created element on the page
that we’ll call the “console.” This function is declared within the imported support
script file (jqia2.support.js), and will save us the trouble of using annoying and disruptive alerts to indicate when things happen on our page. We’ll be using this handy function in many of the examples throughout the remainder of the book.

Related

running code in another function's scope (JavaScript)

So I'm working on a sort of JavaScript framework, just some utility things for myself to use in future projects, and I want to make a data binding system.
The first method I used was objects, and the code would just loop through the specified html element and look for occurences of {{key}} in the markup and then look for that key in the object and replace it that way in the HTML.
For example, if you had <div>{{name}} is a cool guy</div> in the HTML and had {name:"joseph"} in the JS then the final product would be displayed on screen as 'joseph is a cool guy'.
However, I decided later to change my method and instead the framework would except a function. So instead of {name:"joseph"} you would give it function(){ var name = "joseph" }.
This obviously looks better and gives a lot better functionality.
I changed the processing function so instead of looking for the key/value pair to replace the {{key}}, it just uses eval on the variable to gets its value.
My problem lies here: How do I run my search/replace code INSIDE the scope of the function the user passes.
If the user defines variables within that function, their values will not be available anywhere else due to scope issues.
I've tried using Function.toString() to actually modify the source code of the function, but nothing's working and it's all very complicated.
(The issues are not due to the actual solution, I think that Function.toString() might work, but due to my implementation. I keep getting errors)
So... What is the best way to run arbitrary code in the scope of another function?
Critera:
Obviously, I can't modify the function because the user is passing it in. (you can't just tell me to add the search/replace code to the bottom of the function)
The variables must stay in the local scope of the function. (no cheating by using window.name = "joseph" or anything)
I am also aware of how terrible eval is so any suggestions as to get it to work are greatly appreciated. Thanks!
Code:
function process(html) {
var vars = html.match( /({{)[^{}]*(}})/g )
// vars = ['{{variable}}', '{{anotherVariable}}']
var names = vars.map( function(x){ return x.replace("{{", "").replace("}}", "") } )
// names = ['variable', 'anotherVariable]
obj = {}
for (var i = 0; i < names.length; i++) {
obj[names[i]] = eval(names[i])
}
for (var p in obj) {
html = html.replace(new RegExp('{{'+p+'}}','g'), obj[p]);
}
return html
}
You should go back to your first method with the object, it's much better. You can still pass a function, but the function should return an object:
function () {
return { name: 'joseph' }
}

Why use the parameters if we can use variables?

Firstly, I'm a beginner, so don't be mad if what I'm saying is stupid.
So, this is the code that is using parameters:
function simpleExample (x) {
document.write ("I love " + x);
}
simpleExample ("my mom.");
And this is the code that doesn't use the parameters:
function simpleExample () {
var x = ("my mom");// Does not use the parameters
document.write ("I love " + x);
}
simpleExample ();
So, the result is the same and... the global and local thing is also the same [both is local right?] So what does the difference?
Sorry if it's a dumb question.
You maybe right if you just want to say you're loving your mom. But, what if you also want to say other persons that you love? You write all that hard code everytime?
the answer is : no.
You just call that function with a parameter. And that's it. Nothing more.
simpleExample("my mom");
simpleExample("my dad");
simpleExample("justin bieber"); //we all hope you don't.
Why use the parameters if we can use variables?
The point is that often we cannot use static (global) or constant variables. Consider your first function:
simpleExample("my mom.");
simpleExample("my dad.");
We are calling the same function multiple times with different arguments. This requires parametrisation of the code in the function that is otherwise the same for all cases.
Using a parameter for a function allows the result of the function (be it a process or a result value) to differ based on an input that is not fixed at the time of writing the function.
Even with your simple example it should be obvious that the simpleExample(x) function with a parameter can be easily reused like so:
simpleExample('my mom');
simpleExample('and my dad too!');
simpleExample('my sister not so much');
This wouldn't be as easy with the variable approach.
Using parameters is the essence of functions.
In the second case, the variable x is local to the scope of the fonction and will never change. That is, the execution of your function simpleExample will always have the same effect (logging "I love my mom" in the console).
The use of parameters allows your function to have an effect dependent to the input. In this case, the person you love can be changed depending of the parameter x.

Fundamental misunderstanding of how Angular handles a snippet?

I'm having a problem debugging some code in an Angular controller. This function is called when a form is submitted on our checkout page. I'm fairly new to Angular, and I'm a bit confused as to what is going on in this function.
$scope.handleStripe = function(status, response){
PayStripe.processPayment(status, response).then(
function(successMessage){
alert('success', successMessage);
Order.recordOrder(Cart.cart.items, Auth.user.uid)
.then(function(){
PostAffiliatePro.reportSale(Cart.cart.getTotalPrice());
Cart.cart.clearItems();
$scope.mode = 'success';
});
}
);
};
Here's what I think is happening line-by-line...
1) We're declaring a function called handleStripe with two arguments: status and response.
2) A method called processPayment is being called and is inside of an object dependency injected into the controller called PayStripe. .then is opened, so the following lines of code will be executed AFTER the processPayment method is called.
3) Running an anonymous function with an argument of successMessage.
4) I'm confused as to what's happening here, as I've never seen alert called with any arguments other than a message. this page on alert is not much help.
5) A method called recordOrder is called from the object Order which is a dependency of the controller.
6-10) After the recordOrder method is called, the cart is cleared, the sale is reported through another method, and the mode variable contained in the controller's scope is updates to the value success.
I've looked through all of the methods associated with these steps, and I still have some questions.
1) Where are all of these arguments being passed in? Are the arguments passed into the functions pre-declared arguments that will be updated by Angular? I.E. are these variables which Angular defines as the process moves through the queue, and whose values are not user-defined?
2) On line #4, I understand that the second argument is from the argument defined in the function, but what is the combination of these two valued inside the alert() function doing?
3) The fix to the bug that comes from this script depends on me being able to change the value of $scope.mode to something different as soon as the handleStripe function is called, however I have tried to insert such a declaration in multiple places that seem logical with results varying from the script breaking, to nothing happening at all. To me it seems that the logical place to put $scope.mode = 'my-value'; would be between current lines #1 and #2, however this produces the affects I mentioned before.
Finally, I feel I may be missing an overall concept, rather than wrestling with syntax. What is this concept called, if I am missing one, and where can I learn to use it?

Check if object exist

I saw many code that began like that
var a=a||{};
Now I know that its check if a exist.
My question is why to check it if its at the first of the code?
I mean the programmer know that a is not exist.
The programmer should know if the variable exists or not.
It's used to mash different pieces of script together without having to keep track of which part of the script is loaded first. Several scripts will have the same piece of code at the start, so they share the same variable.
For the first script, the variable is declared, and there is no previous value for it, so the {} value is used.
For the following scripts that use it, the var is ignored as the variable is already declared, and the previously set value of the variable is used.
Of course, declaring the same variable in several places has a code smell to it. Preferrably you should keep track of what you are doing so that you only declare it once.
Translated into clearer code
var a; // The variable declaration gets brought up because of hoisting
More info on hoisting here
if( a ) {
a = a; // if a is a truthy value then assign it to itself
} else {
a = {}; // if a is a falsy value then set the default to an empty object
}
Hope that helps
That's a shortcut to fall back on a default value - {} in this case.
Basically, javascript can be written in multiple files and within each file you can have multiple declarations and functions defined.
Even if the programmer knows for a given instance if the variable exists or not, there is no way to know if it already exists when this code is called from somewhere else.
This should not happen in well written code (all from one developer / house) but it does happen in projects where the js code is amalgumated from multiple places.
This SO question has a very nice answer about variable scopes in javascript, it should clarify your doubts.

Why is dynamically modifying a JavaScript function's code mid-execution a bad thing?

A few days ago, I asked a question regarding dynamically modifying a function's code midway through the outerlying script's execution and I was told to completely forget ever coming upon the notion. I'm not sure I understand why that is. Let me give an example:
<script>
var display = function(msg)
{
alert(msg);
}
// Now, at the moment, the display() function
// is receiving a single parameter and alerting
// it to the user. I'm now going to use eval()
// to modify the display() function.
eval('display = ' + display.toString().replace('alert(', 'document.write('));
// Now, the display() function writes its parameter
// to the document as opposed to alerting it.
</script>
I realize this is a rather trivial example, but there must surely be some use that can be derived from being able to dynamically modify a function, something so useful by itself.
Although this may do what you need it to do, 6 months from now you (or the person maintaining your code) will be going "WTF?!"
If your use case is to alert or write based on some condition, why don't you write two different functions? Or have your function take another parameter that decides the output mode. Or pass in a function as a parameter that performs the actual output. Something, you know, a little more on the sane side. ;-)
There are cases where it could be useful to change a function's behavior, but there are better ways to do it. In your example, you could create new instances of the function that handle the output differently, by passing a function as an argument (similar to the strategy pattern):
function makeDisplay(displayStrategy) {
return function(msg) {
// I'm assuming you would do some additional processing here...
displayStrategy(msg);
}
}
var display = makeDisplay(alert);
// now modify display to use document.write
display = makeDisplay(function(msg) { document.write(msg); });
Well, using eval might be a security concern but modifying a function in real-time is ok. How else you can make memoization anyway?
Although, come to think of it, changing method signature isn't a great idea, other people won't know how to call this function after this, since it would depend on execution order and it's not easy to track usually.
I have found myself needing to do this in situations where I don't have the source code for a particular piece of vendor javascript; so that could be a legitimate use case. I agree that if you have another option, it's better to do it in a more organised way, editing the original function to be more flexible.

Categories