...

View Full Version : Did you know...



rdspoons
02-11-2012, 01:05 PM
<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>

felgall
02-11-2012, 10:16 PM
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:


(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).

venegal
02-12-2012, 12:13 AM
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.

felgall
02-12-2012, 07:19 PM
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'.

rnd me
02-12-2012, 11:14 PM
+new Date is a numeric unix timestamp:

+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:

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:

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:


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.

rdspoons
02-13-2012, 08:34 PM
If you only need firefox, you can store block strings directly using a throw-away-root element.



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.

rdspoons
02-16-2012, 10:54 PM
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.");

rnd me
02-17-2012, 07:26 PM
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) (http://danml.com/sandbox/#[1,2,3,4,5].filter%28%C6%92%20a%2%20;;;%29).

rdspoons
02-17-2012, 09:23 PM
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

rnd me
02-18-2012, 04:36 AM
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:

[1,2,3,4,5].filter(ƒ a%2 ;;;) //ƒ's args=(a,b,c)
live test (danml.com/sandbox/#{%22auto%22:%225%22,%22IN%22:%225%22,%22CODE%22:%22[1,2,3,4,5].filter(%C6%92%20a%2;;;)%20//%C6%92%27s%20args=(a,b,c)%22})

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.");
live test (danml.com/sandbox/#{"auto":1,"IN":"5","CODE":"var = = 1;\nvar α = = Γ = π = Σ = σ = = τ = Φ = Θ = Ω = δ = φ = 2;\nvar ε = ⁿ = 3;\nvar Ω1 = \"320\",Ω2 = \"44K\",Ω3 = \"2M\";\nalert(\"You need \"+[Ω1,Ω2,Ω3].join(\"Ω,\")+\"Ω resistors for this project.\");"})



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

[].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:


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:

javascript:%20%5B%5D.slice.call(document.querySelectorAll(%22pre.alt2%22)).map(function(elm)%7B%20%2 0%20var%20a%3Ddocument.createElement(%22a%22)%3B%20%20%20var%20txt%3Delm.textContent%7C%7Celm.innerT ext%3B%20%20%20a.href%3D'http%3A%2F%2Fdanml.com%2Fsandbox%2F%23%7B%22auto%22%3A1%2C%22CODE%22%3A'%2B encodeURIComponent(JSON.stringify(txt))%2B'%7D'%3B%20%20%20a.innerHTML%3D%22Open%20in%20sandbox...%2 2%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)

rdspoons
02-18-2012, 09:15 AM
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.



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



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){}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum