I'm working on a form that does changes on the fly and I'm trying to understand it better.
nonetheless, I came upon and input that has this and I was wondering what does this statement means any example would be appreciated. Thank you
onclick="if(this.onchange){this.onchange();}"
This is checking to see if this has a function defined as onchange. In javascript, you don't need if (this.onchange != null). If the value is null, undefined, or has an empty string, the value in the if statement returned is false. This is usually a good practice to avoid null reference errors in javascript when you aren't positive that every browser is going to support whatever you're attempting to use. (or other reasons I'm missing now)
For example, when adding a line to output to the console in Google Chrome...
console.log("output here");
This may cause errors in other browsers if I remember correctly. A good way to handle this would be to use:
if (console) { console.log("output here"); }
In simple terms,
"If this element has function associated to it's onchange event listener, execute it.".
It's a way to check if it is declared
if (typeof this.onchange != "undefined"){
this.onchange();
}
Related
I am reading a very comprehensive javascript programming book. In the "functions" section of language basics I have come to the following:
"The return statement can also be used without specifying a return value. When used in this way, the function stops executing immediately and returns undefined as its value. This is typically used in functions that don’t return a value to stop function execution early, as in the following example, where the alert won’t be displayed:"
function sayHi(name, message) {
return;
alert(“Hello “ + name + “, “ + message); //never called
}
I am trying to understand why anyone would want to do this. Why write a function that returns "undefined"? I have tried googling, and searching SO, but have not had much luck though this may be because I am not phrasing my search correctly as I am learning js.
Can anyone give me a real-world example of where this might be useful so that I can understand?
Usually it's a conditional return. Something like
function calculateSomething(obj, condition) {
if (condition !=0 ) return;
obj.data = obj.data * 42;
}
in this case if some condition fails - function exits right away. Otherwise data in a passed object is modified.
The function you provide is useless...
However, not every function needs to return something. Sometimes a function does things "elsewhere" and the value that is returned is irrelevant.
The function may have side effects, such as altering the state of the page. Then, the caller may not expect any return value.
In my opinion, learned from masters so to speak, the idea here is to only temporarily disable the function. So if you have like an x amount of function calls to sayHi() like for example in a repeater or spread out over multiple files, the idea can be useful to simply return; without a value. Useful? Yes, to avoid commenting out chunks of code, but that's it.
Leaving this in a development environment, which initially will enter the www, you should not write it like this, and always make sure that: when a function has to return "something", then "something" always counts for value, no matter what the condition. With lowest value a boolean => return false;. This counts for every code block inside that function => for if else while ...
/* INCORRECT: it only returns something conditionally */
function do(something){
if (condition){
return false;
}
}
/* CORRECT: it returns value no matter what the condition */
function do(something){
if (!condition){
return true;
}
return false;
}
/* OPTIMIZED: a lot of ideas can be optimized, especially when returning booleans */
function do(something){
return !condition;
}
The rules only apply if you want to write proper code. Using tools like jslint, jshint or re-sharper helps a lot in understanding the basic principles of writing ecmascript valid code. Since not everyone is aware of these rules, all examples will yield the same result. In the sens of "it works, but it's not valid code".
Because A JS function is an object(has:Attributs+methods)
And , An object should have a value which can be undefined .
The proof is that
function sayHi(){}
Can be handled such as object even calling it :
var returnedValue=sayHi.call() ;
If sayHi does not return anything, returnedValue will be undefined
Example if you want to use classes I am sure about it you will use setter functions to give value for an instance attribute.
Like this:
function Something(val) {
this.value = val;
}
I have a custom object that takes a jQuery object as an argument. What is the best way to handle stopping the instantiation of the object if an invalid datatype is passed.
var MyObj = function( $obj ) {
if( ! ($obj instanceof jQuery) )
return false // This is where it should cancel or error or something
}
var myInstance = new MyObj( 'invalid' );
I guess the best way to tell the user that something is wrong is to throw a new error like that :
throw new Error('Wrong object type');
But it really depend on your goal.
Example, jQuery doesn't trow an error when you pass invalid argument to his constructor, it just return an empty object and the code continue.
After seeing Cal Markham answer, i am a little bit confused about your question.
If your are looking why your code doesn't work, just comment and ill delete that answer since it does answer your current question.
The best way to handle an exceptional situation depends on the particular circumstances of your code. In some cases, when you have the option, you can continue execution in a non-surprising way. In others, when you can't return a meaningful object, you should throw an error. The best guideline is that your code shouldn't surprise the person using it.
An example of an exceptional situation handled in a non-surprising way is in jQuery:
$('#myDiv').css('color', 'red');
Suppose that there is no #myDiv, you could throw an error to alert the developer that he's trying to change the color of an inexisting element. Or you could silently ignore it. jQuery chose the second option and made it work in a coherent, non-surprising way.
The advantage of throwing errors sooner is that the developer needs less time debugging when something goes wrong. The disadvantage is that the code will probably be messier.
The code you have would work fine, just a little syntax error for instanceof. It should be
if( ! ($obj instanceof jQuery) )
I've had numerous bugs happening just because of a missing return in a function. You see, when most of the code you write is in Ruby, it's easy to forget about explicit returns.
So I'd like to use something similar to JSlint (which I already use) to check that all functions return something. Yes, I think it's better to explicitly return something when it's not required than to hunt down missing returns.
So, are there any tools that would check for returns? Or maybe I can assert it in runtime in a simple manner?
Please don't suggest Coffeescript, I'm aware of its existence.
JSUnit example:
<script language="javascript" src="jsUnitCore.js"></script>
<script language="javascript">
function testWithValidArgs() {
assertEquals("someFunction should return something", "Expected REturn Value", someFunction(2, 3));
}
</script>
Just add return consistently. But to be honest, JSlint is a VERY strict checking tool. You will never get errors if you're not returning values unless you're trying to define a variable using the response of a function, but in that case it's more than logic that you add a return statement.
However, if you're still dedicated to have a return statement in every function, you should add them from the start. There is no tool that adds them.
I'm not aware of any tools that will do this out of the box. But it would not be hard to write one.
Start by using UglifyJS to parse your code into a syntax tree. Write a recursive function that examines all code, looking for function definitions. For every function you find, look at the last statement. If that one is not a return-statement, then print a warning.
(Too long for comment.)
My problem with returning something when a function has no (meaningful) return value is that it's misleading, unless it returns undefined, which defeats the purpose.
If I see a return, I have to reason about the code both in the method and at the call site.
In the function I have to determine if it ever returns anything else, why it returns the value it does, etc. The only real way around this is to return a constant that makes it obvious the it's not really returning anything, it's just to satisfy a desire to return something.
At the call site, if a return value is ignored, I need to understand why, and if it's okay to do so. If I know every function returns something, I then have to check the function to see if it's returning that special value, or go through the above process.
I'd almost rather namespace my functions into "function" and "method" namespaces at that point as a differentiater. This would allow automated testing of each namespace to make sure that all functions return something useful, all methods specifically don't, and would provide a source-level clue as to which the caller should expect.
I just got the following error in a piece of javascript (in Firefox 3.5, with Firebug running)
cannot access optimized closure
I know, superficially, what caused the error. I had a line
options.length()
instead of
options.length
Fixing this bug, made the message go away. But I'm curious. What does this mean? What is an optimized closure? Is optimizing an enclosure something that the javascript interpretter does automatically? What does it do?
I had this issue too when Firebug is running.
It seems to happen sometimes, when an exception is raised (for whatever reason) and when there's a recursive function call somewhere in the call stack. The exception gets re-raised as the mysterious "InternalError: cannot access optimized closure"
Changing the way I define the recursive function, seems to make this issue go away. eg changing from
function foo(bar) {... foo(recursively); ...}
to
var foo = function(bar) {... foo(recursively); ...}
Hope that helps.
It is a bug in Firefox happening with Firebug open:
https://bugzilla.mozilla.org/show_bug.cgi?id=505001
[An earlier answer mentioned this was due to this other bug, which I think is incorrect as that other problem was not related to Firebug.]
Seems like a Firefox bug:
https://bugzilla.mozilla.org/show_bug.cgi?id=496790
A closure is a function with context. If you dynamically create a new function, then you create a closure.
function makeAdder(int num) {
return function(int num2) { return num + num2; }
}
adder = makeAdder(5);
adder(7) // returns (5+7) = 12
adder(2) // returns (5+2) = 7
Here, the closure is the inner function, as returned by makeAdder, along with the '5' that was passed.
The javascript engine might choose to optimize away the function shown above, to make things run faster, never generating or running that code, so it can't be debugged or referenced. Optimizers are supposed to be very careful to ensure there's no impact, so I'd guess this one made a mistake.
http://ludex-marketing.com/blog/2009/12/google-analytics-javascript-error-cannot-access-optimized-closure-in-ga-js/
This can also be caused by a simple race condition. I was just refactoring a 'startup' object that does a few things before the document is ready. As soon as I tried to access a second object defined immediately below the startup object I received this error.
I was under the impression that script execution waited until all of the code was compiled. Clearly that's not the case. Waiting for document ready to call methods on the second object fixed the problem. Also, using this nice 'dump()' function confirms that the second object is only partially defined when the error occurs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
I encountered the same error today. In my case this occurred because I was referencing an object's attribute or function that did not exist or was not available. I'm guessing that since the object was available via a closure that was optimized, firebug could not access metadata on that object and thus the cryptic error message.
This also happened to me today. Firebug error'd at line 2 of this function:
function IsValidDate(objName) {
re = new RegExp('^( +|today|pdate|- *\\d+ *(day(s|)|week(s|))+ *$', 'i');
if (re.test(objName.value)) return 2;
return (chkdate(objName));
}
When I added "var " before the declaration of "re" in line 1, the error went away.
There is an exception being raised somewhere else in your code within the function that has this error. It could be as simple trying to access a variable that doesn't exist.
I think we need to get a Firebug dev in here to answer why it doesn't give a more specific error as to where in the closure that raised the exception to prompt the error.
You pasted options.length(), but it is not what prompted the error. What caused the error is the fact that your bug was inside a closure.
function(){
array.length()
}
that gives the error
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.
Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?
function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
if(typeof(thisShouldBeAString) === 'string') {
throw('foo(var), var should be of type string');
}
#yadayada
}
I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.
EDIT
To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?
The problem with type checking is that its actually quite hard to do. For example:-
var s = new String("Hello World!");
alert(typeof s);
What gets alerted? Ans: "object". Its true its a daft way to initialise a string but I see it quite often none-the-less. I prefer to attempt conversions where necessary or just do nothing.
Having said that in a Javascript environment in which I have total control (which is not true if you are simply providing a library) I use this set of prototype tweaks:-
String.prototype.isString = true;
Number.prototype.isNumber = true;
Boolean.prototype.isBoolean = true;
Date.prototype.isDate = true;
Array.prototype.isArray = true;
Hence testing for the common types can be as simple as:-
if (x.isString)
although you still need to watch out for null/undefined:-
if (x != null && x.isString)
In addition to avoiding the new String("thing") gotcha, this approach particularly comes into its own on Dates and Arrays.
Some small remarks on type checking - it's actually not that complicated:
Use typeof to check for primitives and instanceof to check for specific object types.
Example: Check for strings with
typeof x === 'string'
or
typeof x === 'string' || x instanceof String
if you want to include string objects.
To check for arrays, just use
x instanceof Array
This should work reasonably well (there are a few known exceptions - eg Firefox 3.0.5 has a bug where window instanceof Object === false although window.__proto__ instanceof Object === true).
edit: There are some further problems with detection of function objects:
In principle, you could both use typeof func === 'function' and func instanceof Function.
The catch is that in an unnamed browser from a big corporation these checks return the wrong results for some predefined functions (their type is given as 'object'). I know of no workaround for this - the checks only work reliably for user-defined functions...
edit2: There are also problems with objects passed from other windows/frames, as they will inherit from different global objects - ie instanceof will fail. Workarounds for built-in objects exists: For example, you can check for arrays via Object.prototype.toString.call(x) === '[object Array]'.
Libraries like jQuery do not inform the user of the error.
If a function is expecting a number, and a user passes a string, the function just returns without doing anything.
That way, you will avoid JavaScript errors popping up on a live website.
PS. Just make sure to always type check your inputted parameters, to avoid JavaScript errors being thrown.
How about throw:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/throw
Also type of does not distinguish between Array, Null, Object very well. Look at the funciton here: http://javascript.crockford.com/remedial.html, plus there are a few other ways to do it.
Personally I would not do the type checking since it is a step that will just add more processing time to the code. If you care about performance, you would want to chop off as many milliseconds of processing time as possible. Good Documentation will cure the need for the check.
What's about just to silently convert string to numeric datatype on function startup?
You always can determine the datatype of 'string'. Can't you?
You could check for some value like "debug=1" set. If there is - you could output errors like alerts. So in development mode user will see them, but on real site he will turn it off. Same way browser will not show you error message - you need to look at JS console.
Also there is FireBug. You could detect that and put FB debug Messages also.