Why does prototyping Function not affect console.log? - javascript

I prototyped Function so that it has a getBody function:
Function.prototype.getBody = function() {
// Get content between first { and last }
var m = this.toString().match(/\{([\s\S]*)\}/m)[1];
// Strip comments
return m.replace(/^\s*\/\/.*$/mg,'');
};
See here for more info.
I tried to test it this way:
console.log(console.log.getBody.getBody());
but received an error: TypeError: console.log.getBody is undefined.
I figured out that maybe this happens because console.log was defined before I actually prototyped Function so I created an empty function x right before the prototyping and tried to call
console.log(x.getBody.getBody());
which worked without a problem. Checking the type of console.log with typeof console.log results in "function". Here's a CodePen to try it out. All of this wasn't really a surprise since it's what I expected except of console.log.getBody to be undefined.
So why does prototyping Function not affect console.log? I'm using Firefox 18.0.1 with Firebug 1.11.1.

This seems to be an issue with Firebug not with Firefox per se. My guess is that Function in Firebug lives in a different scope then Function in your page. (since unlike the other browsers Firebug is an extension , not a built in browser tool)
In fact if instead of Firebug you use the built in Firefox console (Ctrl+Shift+K), your code works perfectly fine.
More information about Firebug internals can be found here
http://getfirebug.com/wiki/index.php/Firebug_Internals
This excerpt may be interesting
When Firebug is detached from Firefox, open in a new or separate
window, the new window has its own scope. In that scope, a few Firebug
script tags compile to create a connection back to the original
browser.xul window. Most important, chrome.js is unique to each top
level window, but the Firebug object used by the detached window is
the object of the parent browser.xul.

Related

Best Practice : Call a function from chrome dev console [duplicate]

In Chrome's JavaScript console, how do I call a function that belongs to a .js file included in the webpage I am viewing?
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName(); and hit return.
An example of where the console will return ReferenceError is putting a function inside a JQuery document ready function
//this will fail
$(document).ready(function () {
myFunction(alert('doing something!'));
//other stuff
})
To succeed move the function outside the document ready function
//this will work
myFunction(alert('doing something!'));
$(document).ready(function () {
//other stuff
})
Then in the console window, type the function name with the '()' to execute the function
myFunction()
Also of use is being able to print out the function body to remind yourself what the function does. Do this by leaving off the '()' from the function name
function myFunction(alert('doing something!'))
Of course if you need the function to be registered after the document is loaded then you couldn't do this. But you might be able to work around that.
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox):
http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
You can invoke it using
window.function_name()
or directly without window like
function_name()
Basically, there are two cases here:
Your function is in global scope. In that case, simply open a console and call it yourFunction()
Your function is scoped inside some other function(s) and is not accessed globally. In that case, you can open a Sources tab, locate your .js file, place a breakpoint anywhere at the bottom of the outer function (you might need to refresh a page after that if the code have already been run) and call yourFunction() in console. Also, while at breakpoint you may do something like window.yourFuncRef = yourFunction in console, to be able to access it later at any time.
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn from the console by doing this:
indirect("imported_fn()");
Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.

firefox / chrome console log of functions

Normally I use ff + firebug and I find extremely useful it's console feature: if you console.log(a_function); you don't see the (IMHO totally useless) function body, but a link to the js source file where the function is defined.
(On https://getfirebug.com/logging they describe it in the "Logging object hyperlinks" paragraph)
but but, is there a way to have the same behaviour on the firefox / chrome "native" console?
You could add console.trace() or even console.log() within the function definition to track it. Something like this:
function something(){
var x = 5 +3;
console.trace();
console.log("FUNCTION SOMETHING");
return x;
}
So, when it shows up in your Chrome console tools, you can see the originating file and line AND click on it to get to that file's source. Not as eloquent as FF Firebug, but it's a start.
I don't know if you have access to these functions and just want an easy way of going from the console to the source file OR truly don't know where the function originates. But this is what I would do. Check out the source for reference!
Source: https://developers.google.com/chrome-developer-tools/docs/console-api#consoletrace
In Chrome if you place your function in the console.dir function, you will get additional information about the function. You can then right click on the function and select "show function definition".
Example:
console.dir(my_function);
I'm not seeing anything in firefox.
Try to use
console.log("test");
It will work on both ff and chrome.
why not console.debug(yourfunc.toString()); ?

Calling a Javascript Function from Console

In Chrome's JavaScript console, how do I call a function that belongs to a .js file included in the webpage I am viewing?
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName(); and hit return.
An example of where the console will return ReferenceError is putting a function inside a JQuery document ready function
//this will fail
$(document).ready(function () {
myFunction(alert('doing something!'));
//other stuff
})
To succeed move the function outside the document ready function
//this will work
myFunction(alert('doing something!'));
$(document).ready(function () {
//other stuff
})
Then in the console window, type the function name with the '()' to execute the function
myFunction()
Also of use is being able to print out the function body to remind yourself what the function does. Do this by leaving off the '()' from the function name
function myFunction(alert('doing something!'))
Of course if you need the function to be registered after the document is loaded then you couldn't do this. But you might be able to work around that.
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox):
http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
You can invoke it using
window.function_name()
or directly without window like
function_name()
Basically, there are two cases here:
Your function is in global scope. In that case, simply open a console and call it yourFunction()
Your function is scoped inside some other function(s) and is not accessed globally. In that case, you can open a Sources tab, locate your .js file, place a breakpoint anywhere at the bottom of the outer function (you might need to refresh a page after that if the code have already been run) and call yourFunction() in console. Also, while at breakpoint you may do something like window.yourFuncRef = yourFunction in console, to be able to access it later at any time.
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn from the console by doing this:
indirect("imported_fn()");
Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.

Is there any way to fake the calling file in Firebug console?

Note: Firebug being Firebug extension and/or Webkit developer tools.
With the faking of calling file I mean the link at the right side of the console output, pointing to the location where the output function (like console.log) is called.
This becomes a problem when you have unified handler for error messaging etc, thus all the console.log calls originate from the same file & linenumber.
Is there any way to fake this information? Or bake such link (pointing to line number) into the firebug console log (providing one has the stacktrace)? Just adding the filename and line number to the end of any log adds noise to the console output, making it messy.
Most modern browsers define a console.log function. How about instead of writing your own error handler, you go ahead and call console.log everywhere you have an error. Then, for the browsers that do not define console.log, you can define it yourself using whatever you want. For instance, if you wanted to alert the error in IE (or FF without firebug installed.. etc) you could use this code:
<html>
<head>
<title>Test</title>
</head>
<body>
<button onclick="throwError()">
Throw Error</button>
<script type="text/javascript">
function throwError() {
console.log("error here!");
}
if (!window.console) {
window.console = {
log: function(e) {
alert(e);
}
};
}
//Added in EDIT: in production add these lines below to overwrite browser's console.log function
window.console.log = function(e) {
alert("production alert: " + e); //or whatever custom error logging you want
};
</script>
</body>
</html>
You can add whatever you want to the console object. I've tested this in IE8 and Firefox, and I'm fairly confident you can make this idea work for whatever set of browsers you support.
EDIT: Looks like you can also overwrite the default console.log function in Firefox, Safari, and Chrome. Just remap the log member of the console object to a new function that does whatever you want while in production.
Taking a brief trawl on the firebug forums it seems to imply that it (sometimes?) looks at the exception to determine what the line number is.
So you may well be able to fake it that way by judicious massaging.
With Firebug there is an option to show the call stack alongside errors.
Click on the down arrow next to the console tab's name to see and activate it.
It causes a 'plus' icon to show to the left of the message, which reveals the stack.
This might get you closer the code that caused the error.
If you will also need to log errors with console.error() to make use of this.
(not sure how compatible this is with chrome though)

variable assignments using jQuery failing in Safari?

I'm using jQuery 1.3.2 and it's breaking under Safari 4 for mysterious reasons.
All of my javascript references are made right before the tag, yet with the following code:
var status = $('#status');
status.change( function(){ /* ... */ } );
The following error is displayed in the Web Inspector:
TypeError: Result of expression 'status.change' [undefined] is not a function.
However the error is not encountered if I eliminate the variable assignment attach the change method directly like so:
$('#status').change( function(){ /* ... */ } );
Why? I need to use variables for this and several other findById references because they're used many times in the script and crawling the DOM for each element every time is regarded as bad practice. It shouldn't be failing to find the element, as the javascript is loaded after everything except and .
Try changing the variable to something other than "status."
It's confusing your variable with window.status (the status bar text). When I typed var status = $('#status') into the debugging console, the statusbar changed to [Object object]. Must be a bug in Safari.
If you put the code inside a function, so that status becomes a function-local variable, it should work.
It's standard practice in jQuery to wrap things in a
$.onready(function() {
});
This makes sure the DOM is loaded before you try to manipulate it.

Categories

Resources