SitePoint Sponsor

User Tag List

Results 1 to 25 of 33

Hybrid View

  1. #1
    SitePoint Guru
    Join Date
    Jun 2009
    Posts
    825
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    PLS PLS PLS explain what a prototype is...

    I thought a prototype was a sort of "proto" object or something, but it turns out it's just a property?

    I'm confused.. why is inheritance such a big deal with JS? (how does inheritance in JS differ from inheritance in Java?)
    (I know all JS objects inherit from a sort of primal, "mother" Object... I used to think this "mother" object was the same as a prototype.. now of course I'm realizing I'm wrong...;-)

    the reason am looking at this now is that I've been learning a lot of JSON lately (and thanks to help from fellow developers right here on SP I have learned a lot, and am finally comfy with JSON -- yay!)

    but I still have "lose ends".....;-)

    such as: how do you list the KEYS of an object in plain Javascript?

    in jQuery it's so simple, as you pass both the key and the value to the $.each() method; in plain, in this loop...

    Code:
     for (var i in data.users)
    what exactly is "i"?? just the index of the kay-value pair, right?

    something like

    Code:
     data.users[i].firstName
    prints the value of the key "firstName", but how do I print the KEY?

    I've been reading up on this here...
    http://stackoverflow.com/questions/2...ascript-object
    (hence my q's about prototypes...


    I frankly don't get any of the examples, tried a few, none worked..

    I'm printing values thus:

    Code:
      
    for (var i in data.users) {
         output+="<li>" + data.users[i].firstName + " " + data.users[i].lastName + " -- " + data.users[i].joined.month+"</li>";
         }
    so how do I do something like

    Code:
      
    for (var i in data.users) {
         output+="<li>" + data.users[i].KEY"</li>";
         }
    ???

    I can't believe how hard this is compared to the beauty of the jQuery $.each() method.....:-o

    meaning:

    Code:
    $.each(val, function(propName,propValue) {	
    	divLeft.append(propName + '<br>');
    });
    and voila!! no fuss no muss.....;-)

    thank you... HAPPY FOURTH OF JULY.....

    thank you....

  2. #2
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,438
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Quote Originally Posted by maya90 View Post
    such as: how do you list the KEYS of an object in plain Javascript?

    in jQuery it's so simple, as you pass both the key and the value to the $.each() method; in plain, in this loop...

    Code:
     for (var i in data.users)
    what exactly is "i"?? just the index of the kay-value pair, right?

    something like

    Code:
     data.users[i].firstName
    prints the value of the key "firstName", but how do I print the KEY?
    The for..in construct is for looping over all the properties of an object. For each property of the object, the property name (or key, if you prefer) is assigned to the variable you supply (prop, in the example below). You can use this to access the property's value using the array syntax: object[key]. Here's an example:
    Code JavaScript:
    var myObj = {
        name: "Steve Jobs",
        company: "Apple",
        email: "sjobs@apple.com"
    }
     
    for (var prop in myObj) {
        if( myObj.hasOwnProperty( prop ) ) {
            console.log(prop + " = " + myObj[prop]);
        } 
    }

    this would output:
    Code:
    name = Steve Jobs
    company = Apple
    email = sjobs@apple.com
    The hasOwnProperty check ensures that we're only iterating the properties of the object and not the object's prototype.

    Quote Originally Posted by maya90 View Post
    I'm confused.. why is inheritance such a big deal with JS? (how does inheritance in JS differ from inheritance in Java?)
    (I know all JS objects inherit from a sort of primal, "mother" Object... I used to think this "mother" object was the same as a prototype.. now of course I'm realizing I'm wrong...;-)
    In Java (as in PHP) you create a class as a 'template' for creating new objects, and your classes can inherit from other classes. JavaScript doesn't have the concept of a class. If you want ObjectB to inherit methods and properties from ObjectA, you have to set Object A as the prototype for ObjectB.

    Here's an example:
    Code JavaScript:
    var Employee = function(name) {
        this.name = name;
     
        this.getName = function () {
            return this.name;
        }
     
        return this;
    };
     
    var Manager = function(name, department) {
        Employee.apply(this, arguments);
     
        this.department = department;
     
        this.getDepartment = function () {
            return this.department;
        }
     
        return this;
    };
     
    Manager.prototype = new Employee();
     
    var dave = new Manager('Dave', 'Frozen Goods');
     
    console.log(dave.getName() + ' manages ' + dave.getDepartment);
    // Outputs: Dave manages Frozen Goods

    Edit: When you try to access a method or property on an object, if it can't be found then JavaScript looks at the object's prototype to see if it can find them there, and so on and so on, back up the prototype-chain.

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by fretburner View Post
    In Java (as in PHP) you create a class as a 'template' for creating new objects, and your classes can inherit from other classes. JavaScript doesn't have the concept of a class. If you want ObjectB to inherit methods and properties from ObjectA, you have to set Object A as the prototype for ObjectB.
    Something that's helpful to note is that prototypical structures can simulate what classes do, but not the other way around. Classes can't do what prototyping does, so prototyping is more flexible than classes.

    Basically all object contain a prototype and a constructor. The prototype is a set of properties (you could call them default values) that exist on those created objects, and the constructor is a function that runs when a new object is created. Also, each object has a hidden reference to a parent prototype, which is what you alluded to earlier.

    I find though that an image can help to replace a thousand words. The following guide on JavaScript object is a must-read, with good information and diagrams helping to explain what prototypes are.
    http://mckoss.com/jscript/object.htm
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #4
    SitePoint Guru
    Join Date
    Jun 2009
    Posts
    825
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Something that's helpful to note is that prototypical structures can simulate what classes do, but not the other way around. Classes can't do what prototyping does, so prototyping is more flexible than classes.

    Basically all object contain a prototype and a constructor. The prototype is a set of properties (you could call them default values) that exist on those created objects, and the constructor is a function that runs when a new object is created. Also, each object has a hidden reference to a parent prototype, which is what you alluded to earlier.

    I find though that an image can help to replace a thousand words. The following guide on JavaScript object is a must-read, with good information and diagrams helping to explain what prototypes are.

    thank you Paul.... I guess I hadn't seen your comment when I posted my previous response....

    ok, so a prototype is a set of default key-value pairs that..... all objects you create in JavaScript have (I mean objs you create in classic fn syntax) ?? I suppose these are inherited when you create an instant of this object with the keyword "new"??)

    so a "prototype" is just this set of default key-value pairs? like local variables in a Java class...??
    (oooopsss.. that would be class variable, as in Java there are no local vars in classes, only in methods.... hmmmm....

    I still don't know what you mean by "parent prototype"... parent of what? prototype is just a list of properties and values.... why don't we just call them default properties or something? (in Java classes they're also referred to as properties (as long as they're static, I suppose.....;-)
    (and are these default key-value pairs inside the constructor or outside it? (& what are they????? ;-) what are these default key-value pairs? is there a list of them? ;-)

    thank you very much for all your help these last few days, Paul....... I really appreciate it....
    (with JSON you have no choice but dig into OO... I still find it a bit hard... not all of it, but some aspects of it.... (I find it harder than Java OOP...)

    and thank you for the url you posted... I will read it tomorrow....

    have a good day.....

  5. #5
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,438
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    The following guide on JavaScript object is a must-read, with good information and diagrams helping to explain what prototypes are.
    http://mckoss.com/jscript/object.htm
    Very interesting article Paul, thanks for sharing. Every time I read another article about prototypes I learn something new!

  6. #6
    SitePoint Guru
    Join Date
    Jun 2009
    Posts
    825
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Code:
    Manager.prototype = new Employee();
    ?????

    oh my gosh, I have never seen this (until today, when I saw in some of the S.O. urls I looked at...)

    wouldn't something like

    Code:
    Manager = new Employee()
    ???

    make "Manager" inherit from Employee?


    like in this example...

    Code:
    function Employee() {
    	this.dept = "HR";
    	this.manager = "John Johnson";
    }
    
    var Jon = new Employee();
         console.log(Jon.manager);
    Jon inherits from Employee, right?

    oh brother....



    also, thank you for the obj code you posted for grabbing obj keys...

    I don't know why, but in my thingie this code prints this:

    1 = [object Object]
    my code:

    Code:
    list = data.users;
    
    for (var prop in list) {
    	if( list.hasOwnProperty( prop ) ) {
    		$('#console').append(prop + " = " + list[prop]);
    	} 
    }
    this other code

    Code:
     data.users[i].firstName
    prints the value fine....

    thank you very much for your response.....

  7. #7
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,438
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Quote Originally Posted by maya90 View Post
    wouldn't something like

    Code:
    Manager = new Employee()
    ???

    make "Manager" inherit from Employee?
    That would make Manager a new instance of Employee. If you mean:
    Code:
    Manager.prototype = new Employee();
    Then what I'm doing is saying that I want Manager objects to have access to the methods and properties of Employee (after all, a manager is a type of employee too).


    Quote Originally Posted by maya90 View Post
    like in this example...

    Code:
    function Employee() {
    	this.dept = "HR";
    	this.manager = "John Johnson";
    }
    
    var Jon = new Employee();
         console.log(Jon.manager);
    Jon inherits from Employee, right?
    No, Jon IS an Employee - the variable Jon holds an object of the type Employee.

    Quote Originally Posted by maya90 View Post
    I don't know why, but in my thingie this code prints this:

    my code:

    Code:
    list = data.users;
    
    for (var prop in list) {
    	if( list.hasOwnProperty( prop ) ) {
    		console.log(prop + " = " + list[prop]);
    	} 
    }
    this other code

    Code:
     data.users[i].firstName
    prints the value fine....
    In this case, users is an array of objects - if you wanted to iterate the properties of those object you need to nest that inside a loop which iterates over the array, something like this:
    Code JavaScript:
    var length = data.users.length;
    for(var i = 0; i < length; i++) {
        var user = data.users[i]
        for (var prop in user) {
    	if( list.hasOwnProperty( prop ) ) {
    		console.log(prop + " = " + user[prop]);
    	} 
        }
    }

  8. #8
    SitePoint Guru
    Join Date
    Jun 2009
    Posts
    825
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    thank you fretburner.. but this still doesn't print... :-(
    (and I don't get an error....)

    but I see what you're saying, I had to loop down one more level to get the list of keys for each user.....

    so when you do this,

    Code:
     for (var prop in user) {
    how does JS know if 'prop' is the KEY or the VALUE?

    thank you very much for your help...

  9. #9
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,438
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Quote Originally Posted by maya90 View Post
    thank you fretburner.. but this still doesn't print... :-(
    There are a couple problems with your JS:
    Code JavaScript:
    for (var prop in user) {
        if( list.hasOwnProperty( prop ) ) {
            $('content').html(prop + " = " + user[prop]);
        } 
    }
    • You're checking if list.hasOwnProperty but you want to be checking the user object.
    • You're missing the hash (id) symbol from your jQuery selector - it should be $('#content')
    • You probably want to be calling .append rather than .html, otherwise you'll only see the last property displayed


    Quote Originally Posted by maya90 View Post
    how does JS know if 'prop' is the KEY or the VALUE?
    It's just the way that particular construct works, it iterates over keys/property names.
    Last edited by fretburner; Jul 5, 2013 at 11:40. Reason: Added additional info

  10. #10
    SitePoint Guru
    Join Date
    Jun 2009
    Posts
    825
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by fretburner View Post
    No, Jon IS an Employee - the variable Jon holds an object of the type Employee.
    oh my gosh, that's right.. I was thinking of when you extend a class in Java.. of course it's not the same as instantiating a class.... oh brother...

    well, instead of bugging you guys any more I will read the url Paul posted yesterday, that you also said was very good....:-)

    thank you all very much for your help....

  11. #11
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,862
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    JavaScript is a prototyping language whereas Java is an object oriented one. Since OO is far more limited than prototyping you can't replicate the prototype structuring in JavaScript in any OO language.

    The Object.create() method was recently introduced into Javascript to simplify the way that inheritence is applied. It allows you to do in one statement what used to take four or five.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  12. #12
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Ahh, and the $.getJSON can be changed to native JavaScript too, thanks to a tiny library called MicroAjax

    HTML Code:
    <script type="text/javascript" src="microajax.js"></script>
    <script type="text/javascript">
    ...
    </script>
    Code javascript:
    microAjax('json/users2.json', function(data) {
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  13. #13
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,438
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Hey maya90,

    I came across another resource over the weekend that I think you might find interesting: http://www.objectplayground.com/

    There's a video explaining, in some detail, how objects, prototypes and inheritance work in JS. There's also a section at the bottom of the page where you can enter your own code and it will visualize the prototype chain for you.

  14. #14
    SitePoint Guru
    Join Date
    Jun 2009
    Posts
    825
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    thank you very much, fretburner.... :-)


Bookmarks

Posting Permissions

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