return alert from function - javascript

please can you tell me why this wont work.
If I call s.A why wont the alert show.
var s = {
A: function () { alert("test A"); },
B: function () { alert("test B"); }
};
s.A;
thanks

Try
s.A();
A is a function. If you just say s.A; all you're doing is emitting the reference to what A is, e.g. if I whack s.A; into Chrome's javaScript console I get the following:
Notice how all it did was output the function definition?
Now, if I say `s.A();' I get what you originally expected - it fires the function:

see it working on jsfiddle. you'll have to add braces to s.A to make it a function-call.
s.A();

You're returning a reference to the function, but it's not being called. To do so, add the braces after s.A:
s.A();

Related

How to call the function from browser console?

I need to call the function from browser console for testing purpose ?
test is working as expected , but test2 is not working
function test() {
alert(0);
}
(function(e, t) {
var test2 = (function() {
alert(2)
})
})
Calling for browser console
test() // its working
test2() // Uncaught ReferenceError: test2 is not defined
There are two basic problems here:
test2 never exists
test2 is defined inside a function which is never called, so it is never defined.
The code would have to actually call the anonymous function it is inside.
However, assuming that is a side effect of you truncating the code for this question and in your real case that anonymous function does get called:
test2 isn't a global
So in order to access it, you need to be in the right scope.
The only way to do that for the console would be to:
open up the sources tab of the browser's developer tools
add a breakpoint inside the anonymous function
run the code until your reach the breakpoint
then use the console to access test2 which is now in scope.
Note that given the structure of that code you might have to put the breakpoint before test2 has a value assigned to it and then step through the code until after it is defined.
Since your test2 var is a function on it's own, no need to wrap them in ().
Copy/paste this into browser console to check;
var test2 = (function() {
alert(2)
});
test2();
Advanced JavaScript: Why is this function wrapped in parentheses?
Should you really want those parentheses, you can call the existing function like so;
(function(e, t) {
var test2 = (function() {
alert(2)
});
test2(); // <-- Run function
})()
//^^ Extra parentheses to instantly run wrapper function

Setting breakpoints on function calls in Chrome Dev. Mode

Is there a way to set breakpoints when specific functions are about to execute?
It needn't be an explicit breakpoint - I just want execution to pause when a console.log() is about to be called.
Or should I resort to this method.
I prefer to accomplish this without modifying my code, or manually setting breakpoints at every console.log.
Yes that's the trick. Create a custom logging function, put debugger in it and call console.log and you have what you wanted:
function log(message) {
debugger;
console.log(message) ;
}
Edit:
You can also replace console.log by a similar fonction that calls the original:
var clog = console.log;
console.log = function(message) {
if(message == '...') {
debugger;
}
clog.apply(console, arguments);
}
This code will affect all log calls within your page. The check is to catch a certain message. Remove it to stop always.
How about call this at the very start that add a pause break for your every console.log?
This replace the original console.log, pause break first, then call the orignal console.log for you. And this will be apply on all console.log calls.
(function () {
var oldLog = console.log;
console.log = function() {
debugger;
oldLog.apply(console, arguments);
}
})();
console.log('hello');

Recognising variables while assigning a function to a variable in javascript

In my jQuery scripts, when the user closes a menu with an animation, I have to call a function after the closing animation is finished. I want to assign this function dynamically by calling a function openStrip() with a parameter. My code looks like:
var FUNCTION_JUST_AFTER_MENU_CLOSE = function(){};
function openStrip(stripId){
FUNCTION_JUST_AFTER_MENU_CLOSE = function(){
createStrip(stripId);
});
}
if I call openStrip("aStripId"), I expect FUNCTION_JUST_AFTER_MENU_CLOSE to be:
// #1
function(){
createStrip("aStripId");
}
whereas my current code gives:
//#2
function(){
createStrip(stripId);
}
i.e, the parameter passed to the function openStrip() is lost while assigning the function() to the variable FUNCTION_JUST_AFTER_MENU_CLOSE.
How can I avoid this.
EDIT: I discovered that my code is actually working. The problem was elsewhere. I got confused because when I looked at Chrome's debugger, it was showing me the function definition as is (#2 in above). But when it actually went down executing that function later in the code, it did evaluate the values of the passed argument, and endedup executing #1.
Thanks for the answer though. I am marking it correct because that is perhaps a better way of assigning the function.
The best way is to return a function, from openStrip like this
function openStrip(stripId) {
return function() {
createStrip(stripId);
};
}
For example,
function openStrip(stripId) {
return function() {
console.log(stripId);
};
}
openStrip("aStripId")();
# aStripId
openStrip("bStripId")();
# bStripId
You can even assign the function objects returned to different variables and use them later on
var aStrip = openStrip("aStripId");
aStrip();
# aStripId
aStrip();
# aStripId

Why is this global variable not recognised in javascript function?

Despite excessive googling I just don't get why my function doSomething does nothing in the situation below. Any idea why it doesn't work?
Many thanks, Gordon
var arrAttend=new object();
arrAttend["Blob"]='hello';
function doSomething() {
alert (arrAttend["Blob"]);
}
It's a typo, you should use new Object (capital O). Or use an Object Literal:
var arrAttend = {Blob: 'hello'};
function doSomething() {
alert (arrAttend.Blob);
}
Two problems :
object isn't defined
you don't call your function
Try this :
var arrAttend= {}; // that's the simplest way to create a new javascript object
arrAttend["Blob"]='hello';
function doSomething() {
alert (arrAttend["Blob"]);
}
doSomething();
Note that the first kind of error is very easily found when you look at the console : an error is displayed. I'd suggest you to use developer tools (for example Chrome's ones) so that you don't develop in the blind. BTW you'd see that using console.log instead of alert is most often more convenient.
Try this :
var arrAttend=new Object();
arrAttend["Blob"]='hello';
function doSomething() {
alert (arrAttend["Blob"]);
}
There's typo error in your code. And an object should be used like follow -
var arrAttend= {
name:'Blob'
};
function doSomething() {
alert (arrAttend.name);
}
doSomething();
Try this:
// create object
var arrAttend=new Object();
arrAttend["Blob"]='hello';
function doSomething() {
alert (arrAttend["Blob"]);
}
// call function
doSomething();

Why is function() needed sometimes in JavaScript?

HTML
<button id='hello'>Click Me!</button>
JavaScript (wrong)
$('#hello').click(alert('Hello, World!'));
JavaScript (correct)
$('#hello').click(function() {
alert('Hello, World!');
}
I'm wondering why the first JS code triggers on the event load instead of click. Can anyone tell me why function() { [code] } is needed for the script to work properly?
In this example, I used jQuery events, but this is not specific to it, for example, I need to use it with setTimeout, too.
The click function expects another function as a parameter.
In the first case you would be passing the result of calling alert('hello world');, which is null.
The second is just a shorthand for:
$('#hello').click(callback);
function callback(){
alert('hello world');
}
Because .click() is a handler. The first argument is a function to assign. But if you actually pass the function with arguments then it will call the function (in this case alert) and then pass it's return value.
Writing $('#hello).click( function() { } )` is basically a short hand for writing:
var myfunction = function() {
// code
};
$('#hello').click( myfunction );
As you can see in the long hand way, it's passed as a reference to the function instead of the function's return value.
Your first example says "evaluate
alert('Hello, World!')
right now, and pass the result as an argument to click. "
The second says "Define a function which will do the alert when I call it, and pass that whole function as an argument to click.
The function() { ... } syntax is how you declare an anonymous function in Javascript. jQuery uses lots of these to specify that some action will be performed later, like when an event occurs. You can think of it as delaying the execution of your function until necessary. Without this syntax, whatever code you place there is evaluated immediately, which is not what you want for an event handler.
You might think, "why isn't JavaScript smart enough to know the difference?" Consider this:
function returnCallback(linkId, data) {
return function(e) {
alert('Clicked on ' + linkId + '. Here is some data: ' + data);
// Maybe do some stuff with e, the event parameter
}
}
$('#some-link').click(returnCallback('some-link', 'some-data'));
$('#other-link').click(returnCallback('other-link', 'different-data'));
This is a contrived example, but it illustrates the power of anonymous functions and closures. This works since returnCallback returns a function.
In the first instance, "JavaScript wrong", you're actually calling alert('Hello, World!') at the point that the script is loaded. Now, the reason you pass the .click function a function is because it can call it at any point. Essentially, you're packing code together to be run (or not run at all) at any point when you put it in a function.
$('#hello').click(alert('Hello, World!')); is attempting to run alert('...') and pass its return value to the .click() function which will not work as expected.
This is because JavaScript evaluates everything and during this process your alert is invoked. You can use anonymous function or you can also use your own custom function as implemented below:
<script language="javascript" type="text/javascript">
$("#mybutton").click(clickFired);
function clickFired() {
alert('click fired');
}
</script>
The parameter required for the .click() function is a Function. Therefore $("#hello").click(function { [code] }); is required. Because there's nothing to return by alert().
The click function here assigns a value to the event handler.
With the first ("wrong") code you're assigning a value of alert('Hello, World!') which is itself a function call, so it's going to be immediately evaluated and hence appear at load.
With the second ("correct") code you're now assigning a new anonymous function which is not executed itself, just instantiated at load. Hence this will work as expected later.
somefunction(alert('hello! world'));
this would mean you want to pass to somefunction the return value of alert("hello! world").
jquery click expects a callback that it should fire upon click on the element. so you put it in a function which does not execute unless someone (here jquery) calls it explicitly.

Categories