www.webdeveloper.com
Results 1 to 4 of 4

Thread: Shared Fields and Prototypical Inheritance

Hybrid View

  1. #1
    Join Date
    Jun 2012
    Posts
    9

    Shared Fields and Prototypical Inheritance

    I'm understanding JavaScript objects better now, so next comes inheritance. I know that you can add a field shared by all instances of an Object by referring to its prototype:
    code:

    function Object() {}
    Object.prototype.field = "blah";



    However, what happens to this concept when inheritance is applied?
    code:

    function SubObject() {}
    SubObject.prototype = new Object();
    SubObject.prototype.constructor = SubObject;
    SubObject.prototype.field = "sub blah";



    When I refer to SubObject.prototype.field, is the field "field" from the superprototype edited, or is a new field shared only by SubObjects created?

  2. #2
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,774
    Because "field" has a string value, no instances of SubObject share the same actual value. They all get copies of the string literal. Now if we do:
    Code:
    function Parent() {}
    Parent.prototype = {
        foo: {}
    };
    Every instance of Parent shares the same instance of the object referred to using the foo property:
    Code:
    var a = new Parent();
    var b  = new Parent();
    
    alert(a.foo === b.foo); // alerts true
    Now:
    Code:
    function Child() {}
    Child.prototype = new Parent();
    Child.prototype.foo = {};
    
    var a = new Parent();
    var b = new Child();
    
    alert(a.foo === b.foo); // alerts false
    All instances of Parent share the same foo property. All instances of Child share the same foo property, but a direct instance of Parent (a) does not share the same foo property as a direct instance of Child (b).

  3. #3
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,774

  4. #4
    Join Date
    Jun 2012
    Posts
    9
    Ah, that makes sense. Okay, thank you!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

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
  •  
HTML5 Development Center



Recent Articles