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.
Page 3 of 3 FirstFirst 123
Results 31 to 43 of 43

Thread: JS fundamentals

  1. #31
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,294
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by Old Pedant View Post
    The second half of that statement is ONLY true of the CLASS ORIENTED languages. If a language doesn't have classes, it can't very well be true that an object is an instance of a class, can it? JavaScript doesn't have classes. So that second half doesn't apply to JavaScript.
    how does javascript not have classes, have i been alseep at the wheel all these years?

    according to http://en.wikipedia.org/wiki/Class_%...programming%29 , a class:
    is a construct that is used to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable its instances to have state and behavior.[1] Data field members (member variables or instance variables) enable a class instance to maintain state. Other kinds of members, especially methods, enable the behavior of class instances. Classes define the type of their instances

    how does that not describe using "new Option(123)" ?

    Code:
    function keys(ob){var r=[], it;for (it in ob){ r.push(it); };return r;}
    function missing(a){return this.indexOf(a)===-1;}
    
    var o= new Option(123)
    var conProps=keys(Option.prototype)
    var instProps=keys(o)
    
    
    alert("o instanceof Option: "+ (o instanceof Option)  ) // shows true, o is an instand of the Option class
    alert("instance missing contructor props? "+conProps.some(missing, instProps)) // false, no constructor props missing from instance
    alert("Inherited elsewhere:\n\n "+instProps.filter(missing, conProps))  // [index,selected,form,text,defaultSelected,value,label,disabled], the instance props missing from constructor, inherited elsewhere
    it seems to me that javascript calls constructors functions classes. This seems to be a type-preserving compiled/scripting distinction more than a mechanical difference.

    Without quibibling over keywords, is there something else that "classes" do that javascript's constructors cannot?
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  2. #32
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,294
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by felgall View Post
    Yes the declarations go at the top - both those declared via the JavaScript var statement AND ALL the HTML that the JavaScript code needs to reference - hence the actual JavaScript code ends up immediately before the </body> tag so that all the declarations it needs to reference go above it.
    you can put them at the top and use the defer and async attribs to achieve the same perceived-performance benefits as a script placed before the closing body tag.

    no matter where you place the script, you shouldn't use free-floating code that expects the document or other tags to be a certain way.


    if you're not using a loading library, i've found the best performance comes from loading all the script aync, and using a wait pattern around anything with a dependency.


    for example:

    Code:
    <script defer async src="jquery.js" /></script>
    <script defer async src="myplugin.js" /></script>
    <script defer async src="mycode.js" /></script>
    where myplugin would look like:

    Code:
    (function _wait(){
     
      if(!window.$){ return setTimeout(_wait, 33); } //depends waiter
    
      $.fn.abc=function(){ return String(this); };
    
    }())


    and mycode looks like:


    Code:
    (function _wait(){
     
      if( !window.$ || 
          !window.$.fn.abc || 
          !(document.body && document.body.firstChild) || 
          document.readyState!=="compete"    ){ 
              return setTimeout(_wait, 33); 
       } //depends waiter
    
      alert(  $("body").abc()  );
    
    }())

    the problem with simply putting tags at the bottom witout using defer and async is that with scripts MOST people use, the scripts wait for "document.ready()", which won't fire until ALL the script tags have been loaded and parsed one-at-a-time. by using defer, or a dom-adder, you can fetch all needed resources at once without halting page rendering. by using a controlled execution instead of plain script-body-execution, those pieces can execute in the proper order no matter which ones arrive first. the above sniffing IS a bit more boiler-plate, but it results in 100% perfect control in all browsers along with top-of-the-line performance on all client machines.

    admitting, some new desktop browsers bend the rules and fetch scripts before they are needed according to the 1995 model, but the browser holds-off on firing the script until the html parser reaches the script tag. Still, this is not all machines, and using defer/async makes even those spanking new browsers a hair faster due to allowing extra internal optimizations in the layout engine: fewer paint events means faster sites and apps.
    Last edited by rnd me; 09-24-2012 at 10:07 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  3. #33
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,155
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Without quibibling over keywords, is there something else that "classes" do that javascript's constructors cannot?
    First of all, don't believe everything you read on Wikipedia. Remember, it's all written by people who have their own axes to grind.

    But are there things that classes in the most popular class-based languages (C++, Java, C#) do that a JavaScript constructor doesn't? Yes. Many things, Inheritance, polymorphism, static members, templates, and more. Can most of those things be simulated in JavaScript? Yes. But they aren't natural and native to JavaScript. There are some very very powerful constructs that are native to those three (and some other) languages that are difficult (if not well nigh impossible, c.f. templates, a.k.a. "generics") to do in JavaScript.

    Please don't get me wrong. I'm not attacking JavaScript; I'm defending it. But I do recognize the very fundamental differences in a class-based language from the principles of prototypes, et al., that JavaScript is built on.

    Use each language for its strengths. Don't try or expect any one language to be all things to all people for all uses.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  4. #34
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,611
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by Old Pedant View Post
    We might say that JavaScript is a prototype-based language except that I think that might imply some limitations that JavaScript doesn't have.)
    Not at all - JavaScript is commonly identified as a prototyping language in order to make it clear that it doesn't suffer from the many limitations that class based object oriented languages have.

    Class based object oriented languages sit about half way between procedural languages and prototyping ones in so far as how flexible and powerful they are.

    Most people restrict their use of JavaScript to what they already know and so most only use the procedural or object oriented subset of what JavaScript and other prototyping languages are actually capable of.
    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. Users who have thanked felgall for this post:

    zygezund (09-26-2012)

  6. #35
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,611
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by rnd me View Post
    you can put them at the top and use the defer and async attribs to achieve the same perceived-performance benefits as a script placed before the closing body tag.
    1. You would use defer OR async - using both together doesn't make any sense since there the defer overrides the async.

    2. Both of these attributes are relatively new and so not all browsers currently support them. This means that if you do use either of them then you need to allow for the fact that some browsers will try to run the scripts straight away.

    3. document.ready becomes completely unnecessary if you place the scripts at the bottom of the body. You then avoid having to wait for the rest of the scripts to load before you can run the ones that are already loaded. This is the benefit of placing the scripts at the bottom that you don't get with any other placement.
    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.

  7. #36
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,155
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Quote Originally Posted by felgall View Post
    Not at all - JavaScript is commonly identified as a prototyping language in order to make it clear that it doesn't suffer from the many limitations that class based object oriented languages have.

    Class based object oriented languages sit about half way between procedural languages and prototyping ones in so far as how flexible and powerful they are.
    Fair enough. Good way of looking at class based languages.

    What I was trying to say is that if you ONLY say JavaScript is a prototyping language it isn't clear, for example, that any object can add members at any time. But if you think that the word "prototyping" covers all that, then no quibbles.

    As a complete aside: One of the things that finally made C++ a usable language, in my opinion, was the addition of templates (referred to as "generics" in Java). It's one feature of C++/Java/C# that I really miss in JavaScript. You can easily argue that JavaScript doesn't need templates because JavaScript is a typeless langauge, but there are uses for templates that I could see even in a typeless language.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  8. #37
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,294
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by Old Pedant View Post
    are there things that classes in the most popular class-based languages (C++, Java, C#) do that a JavaScript constructor doesn't? Yes. Many things, Inheritance, polymorphism, static members, templates, and more. Can most of those things be simulated in JavaScript? Yes. But they aren't natural and native to JavaScript.
    thanks for replying. i hear the class warfare against javascript a lot, and always wondered what i've been missing sticking to js.

    honestly, i was hoping for a little more. not from you, but from the other languages. it seems there's no "killer app", at least not from going through the list you provided. I'm not sure i grok "simulated in javascipt", sounds pejorative and judgmental to me; either something works or it doesn't.


    I would accept "has to use eval()" as a "working simulation" to provide some distinction. After-all, we see that actionscript, java, php, and coffeescript can all compile into JS (google it), and all of those languages define the "class" keyword. All of those projects use eval instead of raw interpretation.


    that aside, i think javascript does the things on the list pretty natively.
    although not enough programmers take it seriously, brendan put a lot of capabilities in such a tiny syntax.


    i spent time going through the list.

    Inheritance is provided by constructors. Consider new Option(), it inherits from Element, Option, HTMLElement, Node, and Object, maybe a couple more. you can even have multiple inheritances, you just can't control them from withing the constructor (eg clashing toString()s).



    polymorphism:
    Code:
    function Animal(name){
      this.name=name; 
      this.talk=function(){alert(this.name);}
    }
    
    function Cat() {
        Animal.apply(this, arguments);
        this.talk= function() {
            return 'Meow!';
        }
    }
    
    function Dog() {
        Animal.apply(this, arguments);
        this.talk= function() {
            return 'Woof!';
        }
    }
    
    $animals = Array(
        new Cat('Missy'),
        new Dog('Lassie')
    );
    
    
    $animals.map(function(animal){
        console.log( animal.name + ': ' + animal.talk() + "\r\n");
    });
    you can also use prototypes, but replacing init() for super.apply() lets you pass arguments to the base constructor, which can be nice, and seems to be the norm. changes to Animal won't be reflected with this approach, but changes to classes in other languages don't really accommodate that either.


    static members, as best i can discern, are supported:


    Code:
    function Animal(name){
      this.name=name; 
      this.talk=function(){alert(this.name);}
    }
    // static member of a class:
    Animal.population=0;
    
    // or, an indelible static:
     Object.defineProperty( Animal, "living", {value: true, enumerable: true});
    these can be called from anywhere, or in the constructor as "arguments.callee.population"...



    which brings me to templates, which i admit i don't fully understand. It seems good for compile-time and type-maintenance, but scripting doesn't really need compilation or strong typing.

    I do think errors could be sooner. visualstudio2012 has some really nice intelisense for js, overloading and all. it can suggest stuff for
    Code:
    $("body").attr("class")
    at each pipe here:
    Code:
    $|(|"body"|)|.attr(|"class"|)|
    as you type. invalid arguments also get bad styled before you can hit enter.
    this ain't your grandma's scripting IDE, and the real future is closer than ever.


    Thanks again for responding, i really appreciate you taking the time to answer such questions. I know they sounded loaded, and maybe they are a lil' bit, but i do want to understand the situation as best as possible, and this helps.


    i still believe, more now than ever, that JS's class/object features aren't that lacking, and i'm sure you still believe that JS doesn't have classes at all, but c'est la vie. perhaps it's arguing semantics, or maybe semantics are everything in programming and i'm missing something huge...

    if you can think of something that classes make easy but requires a whole mountain of JS, I would love to dig into some examples.


    Class is on the table for ES6:

    Code:
    class Monster extends Character {
      constructor(x, y, name) {
        super(x, y);
        this.name = name;
        this.health_ = 100;
      }
    
      attack(character) {
        super.attack(character);
      }
    
      get isAlive() { return this.health > 0; }
      get health() { return this.health_; }
      set health(value) {
        if (value < 0) throw new Error('Health must be non-negative.');
        this.health_ = value;
      }
    }
    and you can even play with it right now.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  9. #38
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,294
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by felgall View Post
    1. You would use defer OR async - using both together doesn't make any sense since there the defer overrides the async.

    2. Both of these attributes are relatively new and so not all browsers currently support them. This means that if you do use either of them then you need to allow for the fact that some browsers will try to run the scripts straight away.

    3. document.ready becomes completely unnecessary if you place the scripts at the bottom of the body. You then avoid having to wait for the rest of the scripts to load before you can run the ones that are already loaded. This is the benefit of placing the scripts at the bottom that you don't get with any other placement.
    1. some like only one or the other. both hits more than async alone...
    2. that's 100% ok with my approach, those browsers just fetch them sync like always.
    3. any tags using async/defer above the script at the bottom can "jump over" the bottom script, so proper execution is still important. ready() should only fire once all the scripts have been loaded and parsed, which makes it useful. unless you use 100% sync loading, in which case your site is going to be slower no matter where or how you place the tags...


    it's all about the blue line.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  10. #39
    New Coder
    Join Date
    Aug 2012
    Posts
    17
    Thanks
    10
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by felgall View Post
    Yes the declarations go at the top - both those declared via the JavaScript var statement AND ALL the HTML that the JavaScript code needs to reference - hence the actual JavaScript code ends up immediately before the </body> tag so that all the declarations it needs to reference go above it.
    Thank you. I thought it was clear for everybody why scripts should be on the bottom of <BODY> not on the top or in the middle.

    My question, actually, was, why not in the <HEAD>, where they could peacefully sleep, until called?
    I think the <head> section was included into HTML mostly for that purpose (to keep executable code sleeping) otherwise I do not see any big reason, rather then decorative, to have this special section of HTML.

    So I "refactor" my initial question.
    Why to keep scripts in the <body>, not in the <head>?
    Monkeys push buttons, humans push their brains
    David Biedny, Photoshop Channel Chops (my first and still the best book on Photoshop. (May be it is the best one, because authors followed their own motto)

  11. #40
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by zygezund View Post
    Why to keep scripts in the <body>, not in the <head>?
    Traditionally everyone placed script tags in the head, because the body was for content and the head was for everything else. It was just "how it was done".

    Actually the script tag is the only thing that can appear in the head and can also appear in the body, everything else (meta, link, style, title, and so on elements) should stay in the head.

    So the best reason for moving script tags out of the head and placed just before the closing body tag is this:

    "A <script src="url"></script> will block the downloading of other page components until the script has been fetched, compiled, and executed. It is better to call for the script as late as possible, so that the loading of images and other components will not be delayed. This can improve the perceived and actual page loading time. So it is usually best to make all <script src="url"></script> the last features before the </body>. An in-page <script> does not have a significant impact on loading time."
    From the guru himself Douglas Crockford: http://javascript.crockford.com/script.html

    So if you're using a lot of JavaScript in external files; for example using a big library with plugins and so on, you will probably improve you page load times by following Crockford's advice.

    If you have the script in the head, it downloads the script before the rest of the page, and so the microsecond that the page has loaded, it can start executing the script. If you have the script at the end of the body, it will load the page first, the page will appear quicker on your screen, and then it will download and execute the script, which leads to a longer gap between the page appearing and the script running.

    But to be candid I don't think it is an issue worth arguing about. It will rarely make any perceptible difference to the user in most situations.
    Last edited by Philip M; 09-25-2012 at 06:18 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  12. Users who have thanked Philip M for this post:

    zygezund (09-26-2012)

  13. #41
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,294
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by zygezund View Post
    My question, actually, was, why not in the <HEAD>, where they could peacefully sleep, until called?
    I think the <head> section was included into HTML mostly for that purpose (to keep executable code sleeping) otherwise I do not see any big reason, rather then decorative, to have this special section of HTML.
    because they don't sleep, they bring the page-load process to a halt as soon as they are encountered. it's better to have that pause happen after the user can see and click the styled html than before they can see anything. for CSS, the opposite it true; you don't want to see any html before it's styled, else you get the much loathed flash of styled content. the better experience is had by waiting for the css.

    of course these are just entry-level guidelines, you need to experiment with different placements and techniques according to your site and audience.

    look at google for example, and see if you can tell why it's source is like that. they have a huge script block inline, in the head.

    of the 100kb, only 10kb is actually HTML, the rest is js and css. some of the css is in the body, and some in the head. they also deliver CSS as json called from an external script tag lading in the middle of the body!

    It's not based on theory, it's based on billions of observations about what works best. Since the navigation timing API came out, chrome's gotten even faster, go figure. so take anything you read or hear with a grain of salt, numbers talk louder than theory.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  14. Users who have thanked rnd me for this post:

    zygezund (09-26-2012)

  15. #42
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,611
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by Philip M View Post
    "A <script src="url"></script> will block the downloading of other page components until the script has been fetched, compiled, and executed. It is better to call for the script as late as possible, so that the loading of images and other components will not be delayed. This can improve the perceived and actual page loading time. So it is usually best to make all <script src="url"></script> the last features before the </body>. An in-page <script> does not have a significant impact on loading time."
    From the guru himself Douglas Crockford: http://javascript.crockford.com/script.html
    In fact that is no longer true - having a JavaScript higher up in the content does not block the downloading of other files in modern browsers. It only blocks the rendering of the following HTML until after any document.write statements in the script have been processed. You can tell the browser that there are no document.write statements in the script using the async attribute - although not all browsers understand that yet.

    You can see this for yourself simply by loading any web page with JavaScript attached higher up in the page while you have the built in browser debugger turned on (or an equivalent extension if you are using Firefox - the only major browser that doesn't have a built in JavaScript debugger) and open on the Network page where it will provide a diagram showing the relative start and end times for the various file downloads - with other files being downloaded alongside the JavaScript..

    The best reason for placing the JavaScript at the bottom is that you know that everything the script needs to reference is loaded first and that the only things that might still be downloading are other JavaScript files that the current one doesn't need in order to run. The script can therefore run almost as early as possible (even before the document.ready is triggered if there are further JavaScripts). The only place where it would run even sooner is if you link each piece of JavaScript immediately after the piece of HTML it needs to interact with.

    The only JavaScript that needs to go in the head is one that is going to redirect to a different page without needing to first display the current page - eg. a framebreaker script that reloads the page outside of any frames.
    Last edited by felgall; 09-26-2012 at 03:24 AM.
    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.

  16. Users who have thanked felgall for this post:

    zygezund (09-26-2012)

  17. #43
    New Coder
    Join Date
    Aug 2012
    Posts
    17
    Thanks
    10
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by felgall View Post
    JavaScript is commonly identified as a prototyping language
    Thank you, It seems, this mostly resolve my initial problem.
    Prototyping, according my web search, is a technology which uses "copy" and then change object instead of inheritance.

    Fine. So that is my plan to use OO approach (some people here prefer the name class based - noway class oriented as the search results point to radicals' web pages about the class struggle ) in JS.
    I should create a HTML/CSS node, (may be invisible) and refer to it by id. If I need a new object I just copy it. If I need an object of subclass, I make a copy, change/add whatever I need and then use it as a base for that subclass.

    Correct?

    If yes, how to code a scenario:
    I need two similar buttons - backgroung-color is blue (the second one or both are created by a copy method)
    If I click one of them, two other buttons appear. They are similar to previous ones, but backgroung-color is red, and no onclick.

    Thanks in advance
    Monkeys push buttons, humans push their brains
    David Biedny, Photoshop Channel Chops (my first and still the best book on Photoshop. (May be it is the best one, because authors followed their own motto)


 
Page 3 of 3 FirstFirst 123

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
  •