Finding undefined variable name string in ReferenceError - javascript

My question is simple, but Javascript VM dependent.
When catching a ReferenceError (in my case when doing eval(...)), how do I get back the actual identifier token from the error object?
Matching for "known" error messages and parsing them seems way too hackish for me, but is the only available option to me right now.
edit: For the moment I'm only "matching" V8 and Firefox by doing this:
catch(e){
if (e.name === "ReferenceError"){
var varname = e.toString().replace("ReferenceError: ","")
.replace(" is not defined","").trim();
foobar(varname);
}
}

You should be able to do this using e.message and matching the text up until the first space.
The following code works in IE7/IE8/IE9/IE10/Chrome and Firefox.
try {
alert(tesssst);
} catch(e){
if (e.name === "ReferenceError" || e.name === "TypeError") { //IE7 uses TypeError instead
var variableName = e.message.substr(0, e.message.indexOf(" "));
//IE7 and IE8 fix (it adds ' around the variable name)
if (variableName.substr(0, 1) == "'" && variableName.substr(variableName.length - 1) == "'") {
variableName = variableName.substr(1, variableName.length - 2);
}
console.log(variableName); //tesssst
}
}
Edit:
Added IE7/IE8 fixes
Edit 2:
With a little regex magic you can change this to the following:
try {
alert(tesssst);
} catch(e){
if (e.name === "ReferenceError" || e.name === "TypeError") { //IE7 uses TypeError instead
var variableName = e.message.match(/^'?(.*?)'? /)[1];
console.log(variableName);
}
}

Related

How to fix the following errors

I implemented spectrum color picker, and I'm trying to fix up the JSLint errors. I have 2 types of errors which I can't seem to fix. Here are the errors:
Unexpected '~'
Unexpected 'in'. Compare with undefined, or use the hasOwnProperty method instead.
Here's the code for the first error:
function contains(str, substr) {
return !!~('' + str).indexOf(substr);
}
Code for second error:
var hasTouch = ('ontouchstart' in window);
function contains(str, substr) {
return str.indexOf(substr) !== -1;
}
var hasTouch = window.ontouchstart !== undefined;

how to create methods in Javascript and OOP

I'm trying to create an object in JavaScript and I'm following Mozilla's tutorial . the tutorial works just fine, but when I apply that technique to my code it doesn't work. (I'm doing something wrong but I don't see it). I coded all my methods and I don't get any errors, I initialize my object and I don't get any errors either, I even call my methods and I don't get errors, but the return value is a string with my code instead of the value that I'm expecting
function JavaScriptObj(id, datatype) {
function initialize(id, datatype) {
if (typeof id === 'number' && id > 1) {
this.theID = id;
} else {
console.error("ERROR: JavaScriptObj.initialize" + id + "is NOT a valid argument");
}
if (typeof datatype === 'string') {
this.data_type = datatype;
} else {
console.error("ERROR: JavaScriptObj.initialize" + datatype + "is NOT a valid argument");
}
}
}
JavaScriptObj.prototype.getSectionName = function(){
var SectionName = "section-" + this.theID;
return SectionName;
};
var person2 = new JavaScriptObj(2, "texteditor");
alert(person2.getSectionName);
this is my jsfiddle
thanks in advance! :-)
Remove the initialize nested function:
function JavaScriptObj(id, datatype) {
if (typeof id === 'number' && id > 1) {
this.theID = id;
} else {
console.error("ERROR: JavaScriptObj: " + id + "is NOT a valid argument");
}
if (typeof datatype === 'string') {
this.data_type = datatype;
} else {
console.error("ERROR: JavaScriptObj: " + datatype + "is NOT a valid argument");
}
}
JavaScriptObj.prototype.getSectionName = function(){
var SectionName = "section-" + this.theID;
return SectionName;
};
var person2 = new JavaScriptObj(2, "texteditor");
alert(person2.getSectionName()); // need to call it too
It looks like you're not actually executing/calling your method. In order to call your method, you need to append parenthesis to the call:
alert(person2.getSectionName());
Small aside -- using console.log() instead of alert() tends to save you a few keystrokes and makes development a bit faster. Also, alert() is a blocking call that stops all other code execution on the page. While that won't make a difference when you're first starting out, it could potentially be a pain point down the road as your javascript ninja skills increase. :)

Assertions in JavaScript

Extensively reading about various assertion frameworks in JavaScript. Is there any kind of de-facto/most common "standard" library/framework? When selecting one - which points are most worth noticing?
The (only) requirement I can think about is close-to-zero performance overhead when in production mode.
Two possible solutions:
Have your build release script remove the Assert lines.
or
Have your build script override the Assert function so it is just an empty function. Downside to this is if you assert call has logic in it [aka assert( x > 100 , "foo" )] than that logic [x > 100] is still going to be run.
Here is what I use:
When I'm working on the code I have initDevMode(); at the top of the file I'm working with, and when I'm ready to release to production, I just remove that line and all the asserts just go to an empty function.
/**
* Log a message to console:
* either use jquery's console.error
* or a thrown exception.
*
* call initDevMode(); before use to activate
* use with:
* assert(<condition>, "message");
* eg: assert(1 != 1, "uh oh!");
*
* Log errors with:
* errorLog(message);
* eg: errorLog(xhr.status);
*/
assert = function(test, msg) { }
errorLog =function(msg) { }
initDevMode = function() {
assert = function(test, msg) {
msg = msg || "(no error message)";
if(!test) {
try {
throw Error();
} catch(e) {
var foo = e;
var lines = e.stack.split('\n');
for(i in lines) {
if(i > 2) {
errorLog(msg + lines[i]);
}
}
}
}
throw("Assertion failed with: " + msg);
};
errorLog = function(msg) {
if(typeof console.error == 'function') {
console.error(msg);
} else {
function errorLog(msg) {
console.log("foo");
setTimeout(function() {
throw new Error(msg);
}, 0);
}
}
};
}
I use the following to replace console.assert when it's unavailable for whatever reason.
It's definitely not a de-facto standard, and it is far from ideal, but it does satisfy your requirement that the assertion not be evaluated in production mode. Also, it shows you the expression that triggered the failed assertion, which aids debugging.
The screwy calling syntax (with a function expression) is there to create a closure, so that the assert function has access to the same variables that its caller had access to.
I suspect that this has high compile-time and run-time overhead, but I haven't attempted to verify that.
function assert(func) {
var name;
if (typeof(ENABLE_ASSERTIONS) !== "undefined" && !ENABLE_ASSERTIONS) {
return;
}
name = arguments.callee.caller;
name = name ? name.name : "(toplevel)";
if (!func()) {
throw name + ": assertion failed: " + ('' + func).replace(/function[^(]*\([^)]*\)[^{]*{[^r]*return/, '').replace(/;[ \t\n]*}[ \t\n]*$/, '');
}
}
Using it looks like:
function testAssertSuccess() {
var i = 1;
assert(function() { return i === 1; });
}
function testAssertFailure() {
var j = 1;
assert(function() { return j === 2; });
}
ENABLE_ASSERTIONS = true;
testAssertSuccess();
testAssertFailure();
HTH!
Take a look to Jascree; basically it is a tool that can remove assertions with almost arbitrary logic from your code. It is handy to use as a batch processor to generate your production code or for a fastcgi-backed scripts directory that you can use when you need to test performance/profile your code.

How to check if object literal is not in page?

I'm trying to check for if my object literal is not in my page.
var today = {
okay : true
}
If this snippet is not in my page I want to check for null or undefined but it kills silently...
if (today.okay == null)
if (today.okay == undefined)
What to do?
The reason it fails (it shouldn't be failing silently, it should be throwing an exception) is that you're trying to retrieve a value from a symbol (today) that may not be defined.
Try this:
if (typeof today == 'object' && today.okay) {
// It's there
}
else {
// It's not there
}
Alternately, of course, you can just handle the exception:
try {
if (today.okay) {
// 'today' is defined and 'okay' is truthy
}
else {
// 'today' is defined, but 'okay' is not truthy
}
}
catch (e) {
// 'today' is undefined
}
My impression is that most JavaScript engines are very fast when it comes to throwing exceptions (this is not true of all environments), but if you anticipate this condition being not unusual (not exceptional), then I would handle it with inline logic, not an exception. Exceptions are for exceptional conditions.
Assuming you require the "okay" to be boolean, the expression you're looking for is:
('object' == typeof today && today.okay === true)​​​

javascript if statement question

function valid()
{
begin_checked = false;
end_checked = false;
alert("begin_checked: " +begin_checked);
alert("end_checked: " +end_checked);
if (document.dd.begin.checked.length == undefined || document.dd.end.checked.length == undefined )
{
alert("In undefined");
}
alert("end");
}
When the if statement is false, it never gets to alert("end") ? When it is true, it executes properly. Why?
There is probably a null pointer exception and you do not have errors outputting to your browser.
You need some output to check:
alert(document);
alert(document.dd);
alert(document.dd.begin);
alert(document.dd.begin.checked);
alert(document.dd.end);
alert(document.dd.end.checked);
If you get undefined from any of those, then your code will not execute properly.
Edit: Also, the other answers here all have good information. Read those as well.
Edit2: Alternative - Surround your code in a try/catch block and alert the error:
function valid(){
try{
begin_checked = false;
end_checked = false;
alert("begin_checked: " +begin_checked);
alert("end_checked: " +end_checked);
if (document.dd.begin.checked.length == undefined || document.dd.end.checked.length == undefined ){
alert("In undefined");
}
alert("end");
} catch (e) {
alert(e);
}
}
Are there any errors in your browsers error console? I'm guessing it's because it's trying to evaluate a property that doesn't exist, this causing it to fail (never getting to the == undefined). You can just check that the property exists or use the typeof to check if it's undefined.
if (!document.dd.begin.checked.length || !document.dd.end.checked.length)
{
alert("In undefined");
}
if (typeof document.dd.begin.checked.length == 'undefined' || typeof document.dd.end.checked.length == 'undefined' )
{
alert("In undefined");
}
http://getfirebug.com/

Categories