SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Sep 2010
    Location
    Brighton, UK
    Posts
    136
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question about object literals and inheritance.

    I'm working on learning Javascript thoroughly, and I've run into something that's bothering me. I thought I'd chuck it out to the community. My question is, why doesn't the following code work:

    Code:
    var father = {
      i: "rudi",
      f: function() {
        alert(this.i)
      }
    }
    
    var son = {
      prototype:father
    }
    
    father.f();
    son.f();
    When I declare an object literal, I'm surely setting properties for the object. Why can I not set the prototype property here? Is prototype a keyword rather than a property?

  2. #2
    SitePoint Addict bronze trophy AllanP's Avatar
    Join Date
    Sep 2010
    Location
    Australia
    Posts
    298
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by goldfidget View Post
    When I declare an object literal, I'm surely setting properties for the object. Why can I not set the prototype property here? Is prototype a keyword rather than a property?
    Your syntax is wrong. You need to make father the prototype using a constructor, then make an instance of the constructor object like this:

    // create father object with property and method
    var father= {i:"rudi", f:function(){ alert(this.i) } }

    // create child constructor linking property i to name
    function child(name){ this.i=name; }

    // make father prototype of child
    child.prototype=father;

    // create instance of child
    var son=new child("Barry");

    // check if father is really prototype
    alert(father.isPrototypeOf(son))
    result: true
    // use father prototype alert function to show son name
    son.f()
    result: Barry


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
  •