Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11

Thread: Did you know...

  1. #1
    New Coder
    Join Date
    Jun 2009
    Posts
    81
    Thanks
    0
    Thanked 8 Times in 8 Posts

    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.

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,479
    Thanks
    0
    Thanked 635 Times in 625 Posts
    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/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #3
    Gtkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    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

  • #4
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,479
    Thanks
    0
    Thanked 635 Times in 625 Posts
    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'.
    Last edited by felgall; 02-12-2012 at 08:40 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #5
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,190
    Thanks
    10
    Thanked 569 Times in 550 Posts
    +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.
    Last edited by rnd me; 02-12-2012 at 10:16 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #6
    New Coder
    Join Date
    Jun 2009
    Posts
    81
    Thanks
    0
    Thanked 8 Times in 8 Posts
    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

  • #7
    New Coder
    Join Date
    Jun 2009
    Posts
    81
    Thanks
    0
    Thanked 8 Times in 8 Posts
    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.");

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,190
    Thanks
    10
    Thanked 569 Times in 550 Posts
    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 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #9
    New Coder
    Join Date
    Jun 2009
    Posts
    81
    Thanks
    0
    Thanked 8 Times in 8 Posts
    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

  • #10
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,190
    Thanks
    10
    Thanked 569 Times in 550 Posts
    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)
    Last edited by rnd me; 02-18-2012 at 04:12 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #11
    New Coder
    Join Date
    Jun 2009
    Posts
    81
    Thanks
    0
    Thanked 8 Times in 8 Posts
    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.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •