Go Back   CodingForums.com > :: Client side development > JavaScript programming > Post a JavaScript

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-11-2012, 12:05 PM   PM User | #1
rdspoons
New Coder

 
Join Date: Jun 2009
Posts: 81
Thanks: 0
Thanked 8 Times in 8 Posts
rdspoons is on a distinguished road
Did you know...

Code:
<h1>Did you know...</h1>
<h2>1) Did you know You can assign properties to objects before the object definition?</h2>
<h3>(only good for named functions)</h3>
<h3>click me</h3>
<h2>2) Did you know You can constrain an index to a range with the modulus operator?</h2>
<script>
anyFunc.cnt=0; //take advantage of a function definitions precedence.
document.getElementsByTagName("h3")[1].onclick=anyFunc;

function anyFunc(){
    	var arr=[];
     	arr[0]="constrain an index";
	arr[1]="to a range";
	arr[2]="with the modulus operator";
	document.getElementsByTagName("h3")[0].innerHTML=arr[anyFunc.cnt++%arr.length] + anotherFunc.pie.green();
}
</script>


<h2>3) Did you know you can assign objects to an object's objects before the object definition?</h2>
<h2>4) Did you know you can iterate through array literals on the fly?</h2>
<script>
(anotherFunc.pie={})["green"]= function(){anotherFunc.cntr=anotherFunc.cntr||0;return " ("+[1,2,3][anotherFunc.cntr++%3]+")"};

function anotherFunc(){}
</script>


<h2>5) Did you know you can execute functions returned from function calls?</h2>
<h3></h3>
<script>
a()();

function a(){
	return function(){
		document.getElementsByTagName("h3")[2].innerHTML="*The text is from a call before the object definition*";
	}
}
</script>


<h2>6) Did you know you can define static variables from inside a function?</h2>
<h3>clicked 0 times</h3>
<h2>click me</h2>
<script>
document.getElementsByTagName("h2")[6].onclick=a;
function a(){
	a.b=a.b||0;
	document.getElementsByTagName("h3")[3].innerHTML="clicked "+(++a.b)+" times";
}
</script>


<h2>7) Did you know you can create modules using self executing functions and closures?</h2>
<h2>8) Did you know you can pass arguments to self executing functions?</h2>
<h2></h2>
<h3>.click() simulates a click, .onclick() runs the onclick event code</h3>
<h3></h3>
<script>
var meth = (function(el){
	var el=el||{};
	el.onclick=function(){
		return this.style.background="navy", 
			this.style.color="white", 
			this.innerHTML="the last item in a comma chain is the active item", 
			"I am returned";
	}
	return{
		kick:function(){
			document.getElementsByTagName("h3")[4].innerHTML=".click(): "+el.click()+"<br />.onclick(): "+el.onclick();
		}
	}
})(document.getElementsByTagName("h2")[9]);
meth.kick();
</script>

<h2>9) Did you know you can create a transient global if needed?</h2>
<script>
document.body.appendChild(glbrs3a24f71=document.createElement("p"),glbrs3a24f71.innerHTML="Hello ",glbrs3a24f71);
glbrs3a24f71.innerHTML+="World ";
delete(glbrs3a24f71);
try{
	glbrs3a24f71.innerHTML+="I don't exist";
}catch(e){
	document.getElementsByTagName("p")[0].innerHTML+="(ERROR: "+e+")";
}
</script>

Last edited by rdspoons; 02-11-2012 at 04:07 PM..
rdspoons is offline   Reply With Quote
Old 02-11-2012, 09:16 PM   PM User | #2
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,447
Thanks: 0
Thanked 496 Times in 488 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Did you know that you have to define things before you can use or reference them when using strict JavaScript? So items 1 and 3 are things you should forget if you do know them because they will not work in strict JavaScript.

In a script I was recently working on I had:

Code:
(function(banDelay,banners) {
   "use strict";
   var i, b, h, banimg, banlist, Ban, rotateBan;
// lots more code here
   for (x in banners) {
// more code here
   }
})(5000,Banners);
and it took me a while to realise that the entire block of code was refusing to run because I had left x out of the var declaration and was trying to use it without defining it first - which is one of the things strict JavaScript does not allow (since it would be creating a global variable which could adversely affect other code).
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
felgall is offline   Reply With Quote
Old 02-11-2012, 11:13 PM   PM User | #3
venegal
Gütkodierer


 
Join Date: Apr 2009
Posts: 2,127
Thanks: 1
Thanked 426 Times in 424 Posts
venegal has a spectacular aura aboutvenegal has a spectacular aura about
Quote:
Originally Posted by felgall View Post
Did you know that you have to define things before you can use or reference them when using strict JavaScript?
That doesn't really apply here, because function declarations are hoisted. But to be fair, it should say "functions" instead of "objects", and I don't see any use in leveraging function hoisting that way.
__________________
.My new Javascript tutorial site: http://reallifejs.com/
.Latest article: Calculators — Tiny jQuery calculator, Full-fledged OOP calculator, Big number calculator
.Latest quick-bit: Including jQuery — Environment-aware minification and CDNs with local fallback
venegal is offline   Reply With Quote
Old 02-12-2012, 06:19 PM   PM User | #4
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,447
Thanks: 0
Thanked 496 Times in 488 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by venegal View Post
I don't see any use in leveraging function hoisting that way.
I don't see any benefit in defining functions that way in the first place - there are so many things you can't do with functions defined that way - such as placing the definition of the function inside an if statement so as to provide different versions of the same function for different situations.

One of the reasons why strict JavaScript requires that things be defined before you use them is to remove a lot of the potentially hard to spot errors that can be made when you just reference things without defining them first. It seems to be an inconsistency in strict mode that you can still define functions that way and have them hoist to the top of rht script whereas strict mode prevents your using any other fields without defining them first using 'var'.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 02-12-2012 at 08:40 PM..
felgall is offline   Reply With Quote
Old 02-12-2012, 10:14 PM   PM User | #5
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,452
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
+new Date is a numeric unix timestamp:
Code:
 +new Date ==
  Number(new Date) == 
 (new Date()).getTime()== 
  new Date().getTime() ; //your clock is too slow for this to eval true, but it is...


parens in "".split( /(regexp)/ ) are not discarded, they are woven:
Code:
needle=/(eve)/;
haystack="good evening everyone!";
haystack.split(needle); //== ["good ", "eve", "ning ", "eve", "ryone!"];


the tilde operator converts "-1 == false" yeilding ops into proper thruthyness:
Code:
haystack="hello world";
needle="missing";
hasNeedle = ~haystack.indexOf( needle );

alert(  Boolean( hasNeedle )  );



// If you don't need firefox (intranet, node.js, asp), you can store block strings of (almost) arbitry content in function comments:

Code:
var strComboCode = function(){/*
	<select size='1' onchange='setDay(this.value, "userSelected");'  id="dayofweek">
		<option>monday</option>
		<option>tuesday</option>
		<option>wednesday</option>
		<option>thursday</option>
		<option>friday</option>
	</select>
*/}.toString().slice(14,-3);

alert(strComboCode); //doesn't work in firefox :(
//the one restriction is that you can't have js/css comments in the stored code.
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.8% IE9:11.4% IE10:6.5%

Last edited by rnd me; 02-12-2012 at 10:16 PM..
rnd me is offline   Reply With Quote
Old 02-13-2012, 07:34 PM   PM User | #6
rdspoons
New Coder

 
Join Date: Jun 2009
Posts: 81
Thanks: 0
Thanked 8 Times in 8 Posts
rdspoons is on a distinguished road
If you only need firefox, you can store block strings directly using a throw-away-root element.

Code:
var h =<doc><h1>Hello Wolrd</h1>
	<p>This, is nice</p>
	<select size='1' onchange='setDay(this.value, "userSelected");'  id="dayofweek">
		<option>monday</option>
		<option>tuesday</option>
		<option>wednesday</option>
		<option>thursday</option>
		<option>friday</option>
	</select>
	</doc>.toString().slice(5,-6);

alert(h); //only works in firefox.
same restrictions as above.

Last edited by rdspoons; 02-13-2012 at 07:35 PM.. Reason: spelling
rdspoons is offline   Reply With Quote
Old 02-16-2012, 09:54 PM   PM User | #7
rdspoons
New Coder

 
Join Date: Jun 2009
Posts: 81
Thanks: 0
Thanked 8 Times in 8 Posts
rdspoons is on a distinguished road
Did you you know that you can use some extended ASCII characters in variable names if desired?

var ª = º = 1;
var α = ß = Γ = π = Σ = σ = µ = τ = Φ = Θ = Ω = δ = φ = 2;
var ε = ⁿ = 3;

var Ω1 = "320",Ω2 = "44K",Ω3 = "2M";

alert("You need "+[Ω1,Ω2,Ω3].join("Ω,")+"Ω resistors for this project.");
rdspoons is offline   Reply With Quote
Old 02-17-2012, 06:26 PM   PM User | #8
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,452
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Quote:
Originally Posted by rdspoons View Post
Did you you know that you can use some extended ASCII characters in variable names if desired?

var ª = º = 1;
var α = ß = Γ = π = Σ = σ = µ = τ = Φ = Θ = Ω = δ = φ = 2;
var ε = ⁿ = 3;

var Ω1 = "320",Ω2 = "44K",Ω3 = "2M";

alert("You need "+[Ω1,Ω2,Ω3].join("Ω,")+"Ω resistors for this project.");
extended ASCII is not 100% portable, so i would avoid using them. Different languages can have different high asciis, depending on the codepage in use on the OS.


The good news is that you CAN however use unicode chars, which are better and more plentiful. What you show looks to be mostly unicode.

I think "~".charCodeAt(0), 126, is the highest ascii char that doesn't get coerced into unicode by the browser.

personally, i use ƒ (ALT+159 on win) for lambda expressions sometimes. in my sandbox, you can code a function as "ƒ ... ;;;": live example (click run).
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.8% IE9:11.4% IE10:6.5%
rnd me is offline   Reply With Quote
Old 02-17-2012, 08:23 PM   PM User | #9
rdspoons
New Coder

 
Join Date: Jun 2009
Posts: 81
Thanks: 0
Thanked 8 Times in 8 Posts
rdspoons is on a distinguished road
Not arguing the valid point on code pages, just listing my log results from the nice sandbox at http://danml.com/sandbox/

-----------
FF

RUN:
[1,2,3,4,5].filter(Æ’ a%2 ;;; )

LOG:
14:07:08 - RUN: 29 bytes

RUN:
var ª = º = 1;
var α = ß = Γ = π = Σ = σ = µ = τ = Φ = Θ = Ω = δ = φ = 2;
var ε = ⁿ = 3;
var Ω1 = "320",Ω2 = "44K",Ω3 = "2M";
alert("You need "+[Ω1,Ω2,Ω3].join("Ω,")+"Ω resistors for this project.");

LOG:
14:08:00 - RUN: 199 bytes

-----------
Chrome

RUN:
[1,2,3,4,5].filter(Æ’ a%2 ;;; )

LOG:
14:09:03 - RUN: 30 bytes
14:09:03 - ERROR: Unexpected token ILLEGAL

RUN:
var ª = º = 1;
var α = ß = Γ = π = Σ = σ = µ = τ = Φ = Θ = Ω = δ = φ = 2;
var ε = ⁿ = 3;
var Ω1 = "320",Ω2 = "44K",Ω3 = "2M";
alert("You need "+[Ω1,Ω2,Ω3].join("Ω,")+"Ω resistors for this project.");

LOG:
14:09:50 - RUN: 199 bytes


-----------

Safari

RUN:
[1,2,3,4,5].filter(Æ’ a%2 ;;; )

LOG:
14:11:42 - RUN: 30 bytes
14:11:42 - ERROR: Parse error

RUN:
var ª = º = 1;
var α = ß = Γ = π = Σ = σ = µ = τ = Φ = Θ = Ω = δ = φ = 2;
var ε = ⁿ = 3;
var Ω1 = "320",Ω2 = "44K",Ω3 = "2M";
alert("You need "+[Ω1,Ω2,Ω3].join("Ω,")+"Ω resistors for this project.");

LOG:
14:12:23 - RUN: 199 bytes

-----------

Opera

RUN
[1,2,3,4,5].filter(Æ’ a%2 ;;; )

LOG:
14:13:16 - RUN: 29 bytes

RUN:
var ª = º = 1;
var α = ß = Γ = π = Σ = σ = µ = τ = Φ = Θ = Ω = δ = φ = 2;
var ε = ⁿ = 3;
var Ω1 = "320",Ω2 = "44K",Ω3 = "2M";
alert("You need "+[Ω1,Ω2,Ω3].join("Ω,")+"Ω resistors for this project.");

LOG:
14:13:51 - RUN: 203 bytes
rdspoons is offline   Reply With Quote
Old 02-18-2012, 03:36 AM   PM User | #10
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,452
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Quote:
Originally Posted by rdspoons View Post
Not arguing the valid point on code pages, just listing my log results from the nice sandbox at http://danml.com/sandbox/
i use it quite often because i can bookmark a code chunk and then try it out on many devices by navigating to the link. it's good for sniffing/debugging new features on mobile devices and other non-firebugish providing browsers.

The [save] button uses localStorage (sandbox has no servercode, just html); i don't backup, store, or steal anyone's code, and the url hashes that contain your code don't appear in my (or anyone's) http logs (just hits to /sandbox/)...

The [export] button produces urls that link to the sandbox's CODE, IN and DATA textareas.


though there is no button for it, alerting the url so that the location.hash JSON has an "auto" property will auto-run the linked code upon landing on the page.

if you only have CODE, you don't have a JSON object on the location.hash only the raw code. Simply click IN (or another unused textarea like DATA), type "1", then click [export] and change "IN" (or whichever) in the url to "auto" to activate auto-run.

RUN:
Code:
[1,2,3,4,5].filter(ƒ a%2 ;;;) //ƒ's args=(a,b,c)
live test

RUN:
Code:
var ª = º = 1;
var α = ß = Γ = π = Σ = σ = µ = τ = Φ = Θ = Ω = δ = φ = 2;
var ε = ⁿ = 3;
var Ω1 = "320",Ω2 = "44K",Ω3 = "2M";
alert("You need "+[Ω1,Ω2,Ω3].join("Ω,")+"Ω resistors for this project.");
live test



EDIT:

since this is the post something useful place, here's a bookmarklet to let you run any plain code on this forum in the sandbox by clicking an added link:

firebug code
Code:
[].slice.call(document.querySelectorAll("pre.alt2")).map(function(elm){
  var a=document.createElement("a");
  var txt=elm.textContent||elm.innerText;
  a.href='http://danml.com/sandbox/#{"auto":1,"CODE":'+encodeURIComponent(JSON.stringify(txt))+'}';
  a.innerHTML="Open in sandbox...";
  a.setAttribute("target","_blank");
  a.setAttribute("style", "clear: both; float: left; color: blue; "+
           "margin-top: 0.3em; margin-bottom: -0.5em; font-size: 14px;");
  elm.appendChild(a);
})

bookmarklet url
I can't post a real bookmarklet link on this forum as a safty measure, but this is the url your bookmark needs to have:

Code:
javascript: [].slice.call(document.querySelectorAll("pre.alt2")).map(function(elm){   var a=document.createElement("a");   var txt=elm.textContent||elm.innerText;   a.href='http://danml.com/sandbox/#{"auto":1,"CODE":'+encodeURIComponent(JSON.stringify(txt))+'}';   a.innerHTML="Open in sandbox...";   a.setAttribute("target","_blank");   a.setAttribute("style", "clear: both; float: left; color: blue; "+            "margin-top: 0.3em; margin-bottom: -0.5em; font-size: 14px;");   elm.appendChild(a); })
escaped:
Code:
javascript:%20%5B%5D.slice.call(document.querySelectorAll(%22pre.alt2%22)).map(function(elm)%7B%20%20%20var%20a%3Ddocument.createElement(%22a%22)%3B%20%20%20var%20txt%3Delm.textContent%7C%7Celm.innerText%3B%20%20%20a.href%3D'http%3A%2F%2Fdanml.com%2Fsandbox%2F%23%7B%22auto%22%3A1%2C%22CODE%22%3A'%2BencodeURIComponent(JSON.stringify(txt))%2B'%7D'%3B%20%20%20a.innerHTML%3D%22Open%20in%20sandbox...%22%3B%20%20%20a.setAttribute(%22target%22%2C%22_blank%22)%3B%20%20%20a.setAttribute(%22style%22%2C%20%22clear%3A%20both%3B%20float%3A%20left%3B%20color%3A%20blue%3B%20%22%2B%20%20%20%20%20%20%20%20%20%20%20%20%22margin-top%3A%200.3em%3B%20margin-bottom%3A%20-0.5em%3B%20font-size%3A%2014px%3B%22)%3B%20%20%20elm.appendChild(a)%3B%20%7D)
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.8% IE9:11.4% IE10:6.5%

Last edited by rnd me; 02-18-2012 at 04:12 AM..
rnd me is offline   Reply With Quote
Old 02-18-2012, 08:15 AM   PM User | #11
rdspoons
New Coder

 
Join Date: Jun 2009
Posts: 81
Thanks: 0
Thanked 8 Times in 8 Posts
rdspoons is on a distinguished road
Quote:
there are so many things you can't do with functions defined that way - such as placing the definition of the function inside an if statement so as to provide different versions of the same function for different situations
1) anyFunc is constructed to hold one version.

Code:
anyFunc.cnt = 0;
(
	document.body.appendChild(
		d=document.createElement("h3"),
		d.innerHTML="CLICK ME",
		d.style.background='#999900',
		d.id="ex001",
		d
	)
).onclick=anyFunc;

function anyFunc(e){
	var f;
	if(window.AudioProcessingEvent){
		f=function(e){
		    	var arr=["I","am","chrome"]; //or AudioProcessingEvent is explicitly defined
			document.getElementById(e.target.id).innerHTML=arr[anyFunc.cnt++%arr.length];
		}
	}else if(window.CSSVariablesDeclaration){
		f = function(e){
		    	var arr=["I","am","safari"]; //or CSSVariablesDeclaration is explicitly defined
			document.getElementById(e.target.id).innerHTML=arr[anyFunc.cnt++%arr.length];
		}
	}else if(window.searchSuggest){
		f = function(e){
		    	var arr=["I","am","opera"]; //or searchSuggest is explicitly defined
			document.getElementById(e.target.id).innerHTML=arr[anyFunc.cnt++%arr.length];
		}
	}else if(window.sizeToContent){
		f = function(e){
		    	var arr=["I","am","firefox"]; //or sizeToContent is explicitly defined
			document.getElementById(e.target.id).innerHTML=arr[anyFunc.cnt++%arr.length];
		}
	}else if(window.execScript){
		f = function(e){
		    	var arr=["I","am","ie"]; //or execScript is explicitly defined
			document.getElementById(window.event.srcElement.id).innerHTML=arr[anyFunc.cnt++%arr.length];
		}
	}else{
		f = function(e){
		    	var arr=["I","am","special"]; //not one of the 5 above
			alert(arr[anyFunc.cnt++%arr.length]);
		}
	}
	f(e);
}

2) anyFunc is constructed to hold different versions based on enviornment

Code:
anyFunc.cnt = 0;
(
	document.body.appendChild(
		d=document.createElement("h3"),
		d.innerHTML="CLICK ME",
		d.style.background='#999900',
		d.id="ex001",
		d
	)
).onclick=function(e){anyFunc.action1(e)};



(function(){
	if(window.AudioProcessingEvent){
		anyFunc.arr=["I","am","chrome"]; //or AudioProcessingEvent is explicitly defined
		anyFunc.action1=function(e){
			document.getElementById(e.target.id).innerHTML=anyFunc.arr[anyFunc.cnt++%anyFunc.arr.length];
		}
	}else if(window.CSSVariablesDeclaration){
		anyFunc.arr=["I","am","safari"]; //or CSSVariablesDeclaration is explicitly defined
		anyFunc.action1=function(e){
			document.getElementById(e.target.id).innerHTML=anyFunc.arr[anyFunc.cnt++%anyFunc.arr.length];
		}
	}else if(window.searchSuggest){
		anyFunc.arr=["I","am","opera"]; //or searchSuggest is explicitly defined
		anyFunc.action1=function(e){
			document.getElementById(e.target.id).innerHTML=anyFunc.arr[anyFunc.cnt++%anyFunc.arr.length];
		}
	}else if(window.sizeToContent){
		anyFunc.arr=["I","am","firefox"]; //or sizeToContent is explicitly defined
		anyFunc.action1=function(e){
			document.getElementById(e.target.id).innerHTML=anyFunc.arr[anyFunc.cnt++%anyFunc.arr.length];
		}
	}else if(window.execScript){
		anyFunc.arr=["I","am","ie"]; //or execScript is explicitly defined
		anyFunc.action1=function(){
			document.getElementById(window.event.srcElement.id).innerHTML=anyFunc.arr[anyFunc.cnt++%anyFunc.arr.length];
		}
	}else{
		anyFunc.arr=["I","am","special"]; //not one of the 5 above
		anyFunc.action1=function(){
			alert(arr[anyFunc.cnt++%arr.length]);
		}
	}
})();

function anyFunc(e){}

Last edited by rdspoons; 02-18-2012 at 12:42 PM..
rdspoons is offline   Reply With Quote
Reply

Bookmarks

Tags
functions, objects, questions, script

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 10:26 AM.


Advertisement
Log in to turn off these ads.