Question about making a property on custom object

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sam Kong

    Question about making a property on custom object

    Hello!

    I got recently intrigued with JavaScript's prototype-based
    object-orientation.
    However, I still don't understand the mechanism clearly.

    [Q1]
    What's the difference between the following two?

    (1)
    function C(){
    this.name = "Unknown"
    }

    (2)
    function C(){
    }
    C.prototype.nam e = "Unknown"



    [Q2]
    There's no notion of Class in JavaScript and everything is an object.
    How many objects are created in the following code including the
    objects implicitly created in the behind?

    function C(){
    }

    function D(){
    }
    D.prototype = new C

    var obj = new D


    [Q3]
    I saw some codes like "this.base = SomeClass".
    When is it needed?
    Is it different from ClassName.proto type = new ParentClassName ?


    [Q4]
    What's the difference between prototype and __proto__?


    Thanks in advance.
    Sam

  • Thomas 'PointedEars' Lahn

    #2
    Re: Question about making a property on custom object

    Sam Kong wrote:
    [color=blue]
    > [Q1]
    > What's the difference between the following two?
    >
    > (1)
    > function C(){
    > this.name = "Unknown"
    > }
    >
    > (2)
    > function C(){
    > }
    > C.prototype.nam e = "Unknown"[/color]

    With (1), the created object owns the property. Meaning that objects
    created through the same constructor may still have different properties
    and property values if they are modified afterwards.

    With (2), the prototype of the created object has the property, so the
    object inherits the property through the prototype chain. Meaning that
    if you modify the prototype property/method `name', all objects created
    through this constructor that do not own a `name' property themselves,
    in a sense have their `name' property modified as in that case the
    prototype chain is accessed on property access.

    This has been explained in more detail very often before, please search
    the archives[1] before you post.
    [color=blue]
    > [Q2]
    > There's no notion of Class in JavaScript and everything is an object.[/color]

    Not true. There is no notion of classes in JavaScript implemented for HTML
    user agents, and there are not only objects but also primitive values.
    [color=blue]
    > How many objects are created in the following code including the
    > objects implicitly created in the behind?
    >
    > function C(){
    > }
    >
    > function D(){
    > }
    > D.prototype = new C
    >
    > var obj = new D[/color]

    Four that are obvious. Two Function objects referred to by C and D each,
    and two Object objects referred to by D.prototype and obj each, where D
    objects (short for "objects created through the D constructor") are Object
    objects that inherit from C.prototype.

    window.alert([C, D, D.prototype, obj]);

    Other implicitly created objects include the Global Object and all other
    core objects. See ECMAScript 3 for details.[2]
    [color=blue]
    > [Q3]
    > I saw some codes like "this.base = SomeClass".
    > When is it needed?[/color]

    When you want to (re)define a property of the object to be created, the
    calling object or the Global Object; which one depends on the execution
    context.
    [color=blue]
    > Is it different from ClassName.proto type = new ParentClassName ?[/color]

    It is completely different from that. The latter makes a ParentClassName
    object the prototype object of ClassName objects, and so makes ClassName
    objects inherit from ParentClassName .prototype.
    [color=blue]
    > [Q4]
    > What's the difference between prototype and __proto__?[/color]

    `prototype' is an identifier defined in ECMAScript for properties of
    Function objects used to refer to their prototype objects.

    `__proto__' is a JavaScript-proprietary identifier for properties of
    all objects created through `new' to refer to the prototype objects
    of their constructors; ISTM that `x.__proto__' is a shortcut for
    `x.constructor. prototype' as documented[3], even though
    `x.__proto__ === x.constructor.p rototype' equals `false'.


    HTH

    PointedEars
    ___________
    [1] <URL:http://groups.google.c om/group/comp.lang.javas cript>
    [2] <URL:http://www.mozilla.org/js/language/>
    [3]
    <URL:http://developer.mozil la.org/en/docs/Core_JavaScript _1.5_Guide:Deta ils_of_the_Obje ct_Model#Inheri ting_Properties >

    Comment

    • Sam Kong

      #3
      Re: Question about making a property on custom object

      Thomas,

      Thank you for the answers.
      They are very impressive and helpful.

      I have a further question.

      Thomas 'PointedEars' Lahn wrote:[color=blue]
      > Sam Kong wrote:
      >[color=green]
      > > [Q1]
      > > What's the difference between the following two?
      > >
      > > (1)
      > > function C(){
      > > this.name = "Unknown"
      > > }
      > >
      > > (2)
      > > function C(){
      > > }
      > > C.prototype.nam e = "Unknown"[/color]
      >
      > With (1), the created object owns the property. Meaning that objects
      > created through the same constructor may still have different properties
      > and property values if they are modified afterwards.
      >
      > With (2), the prototype of the created object has the property, so the
      > object inherits the property through the prototype chain. Meaning that
      > if you modify the prototype property/method `name', all objects created
      > through this constructor that do not own a `name' property themselves,
      > in a sense have their `name' property modified as in that case the
      > prototype chain is accessed on property access.[/color]

      See the following code.

      function C(){
      this.name = "Test"
      }

      function D(){
      }
      D.prototype = new C

      var obj = new D
      obj.name = "Test2" //HERE, I HAVE A QUESTION.

      function C(){
      this.name = "Test"
      }

      function D(){
      }
      D.prototype = new C

      var obj = new D
      obj.name = "Test2"

      At the last line, does it add a new slot for the property or does it
      modify the value of existing property 'name'?

      Thanks.

      Sam

      Comment

      • zwetan

        #4
        Re: Question about making a property on custom object

        Hello,

        "Sam Kong" wrote:[color=blue]
        >
        > I got recently intrigued with JavaScript's prototype-based
        > object-orientation.
        > However, I still don't understand the mechanism clearly.
        >
        > [Q1]
        > What's the difference between the following two?
        >
        > (1)
        > function C(){
        > this.name = "Unknown"
        > }
        >
        > (2)
        > function C(){
        > }
        > C.prototype.nam e = "Unknown"
        >[/color]

        when you will instanciate an object

        foobar = new C();

        with (1) the property "name" will be explicitly copied into the instance

        with (2) the property "name" will be inherited by delegation
        meaning the instance "foobar" does not have a copy of the property "name"
        but can access it following the prototype chain

        if you create 10 instances
        wiht (1) you have 10 different "name" properties
        with (2) the "name" property is shared by every instances
        [color=blue]
        >
        > [Q2]
        > There's no notion of Class in JavaScript and everything is an object.[/color]

        no but you have notion of constructors which can "emulate" classes

        cf ECMA-262 4.2.1
        "ECMAScript does not contain proper classes such as those in C++, Smalltalk,
        or Java, but rather, supports constructors which create objects by executing
        code that allocates storage for the objects and initialises all or part of
        them by assigning initial values to their properties. All constructors are
        objects, but not all objects are constructors. Each constructor has a
        Prototype property that is used to implement prototype-based inheritance and
        shared properties. Objects are created by using constructors in new
        expressions; for example, new String("A String") creates a new String
        object. Invoking a constructor without using new has consequences that
        depend on the constructor. For example, String("A String") produces a
        primitive string, not an object."

        see http://www.ecma-international.org/pu...s/Ecma-262.htm
        [color=blue]
        > How many objects are created in the following code including the
        > objects implicitly created in the behind?
        >
        > function C(){
        > }
        >
        > function D(){
        > }
        > D.prototype = new C
        >
        > var obj = new D
        >[/color]

        for the segment of code above

        4 if you consider the creation of a prototype property as
        not-an-object-instanciation

        function are objects, once you declare one you create an object
        when you use the "new" keyword you instanciate an object

        5 if you consider that the creation of the prototype property is an object
        instanciation

        function C in the behind automatically define a "prototype" property
        which is equivalent to
        C.prototype = Function.protot ype;

        see ECMA-262 13.2 Creating Function Object
        "
        [...]
        4. Set the [[Prototype]] property of F to the original Function prototype
        object as specified in section 15.3.3.1.
        [...]
        9. Create a new object as would be constructed by the expression new
        Object().

        10. Set the constructor property of Result(9) to F. This property is given
        attributes { DontEnum }.

        11. Set the prototype property of F to Result(9). This property is given
        attributes as specified in section 15.3.5.2.
        [...]
        NOTE A prototype property is automatically created for every function,
        to allow for the possibility that the function will be used as a
        constructor.
        "

        and




        just writing
        function C() {
        }

        DO create
        C.prototype = new Object();

        [color=blue]
        > [Q3]
        > I saw some codes like "this.base = SomeClass".
        > When is it needed?
        > Is it different from ClassName.proto type = new ParentClassName ?
        >[/color]

        could you provide some code constructs ?

        I will try to "guess"...

        usually when you want to inherit a constructor

        you can do

        function A(){
        }

        function B(){
        }

        B.prototype = new A();

        but doing that you override the original B "prototype" property
        and so you override also the "constructo r" property contained in "prototype"

        foo = new A();
        //foo.constructor == A

        bar = new B();
        //bar.constructor == A, and not B

        to correct this behaviour you can reassign the constructor property after
        overriding the prototype

        function B(){
        }

        B.prototype = new A();
        B.prototype.con structor = B;

        so now when you instanciate an objet with the B constructor function

        bar = new B();
        //bar.constructor == B


        for the "this.base = SomeClass".
        I suppose you seen that in that context to emulate superClass constructor
        call

        function A( x ){
        this.x = x;
        }

        function B( x, y ){
        this.base = A;
        this.base( x );
        this.y = y;
        }

        B.prototype = new A();

        in this case "this.base" allow to execute A constructor inside the B
        constructor
        but with the B function scope, so the "x" is created in the context of B and
        not A

        alternatively you can also do that

        function B( x, y ){
        A.call( this, x ); // equivalent to "super( x )"
        this.y = y;
        }

        B.prototype = new A();

        [color=blue]
        > [Q4]
        > What's the difference between prototype and __proto__?
        >[/color]

        first let's define a context

        function A(){
        }

        foobar = new A();

        in the context of "foobar"
        foobar.prototyp e does NOT exist
        foobar.construc tor is a pointer to A constructor function (hence the name)
        foobar.__proto_ _ is a pointer to A.prototype object

        in the context of "A"
        A.prototype is an instancied object
        (see above "9. Create a new object as would be constructed by the expression
        new Object().")

        here what we obtain with JSDB (www.jsdb.org)
        ------------------------------------
        function A()
        {

        }


        foobar = new A();

        println( foobar.construc tor === A ); //true
        println( foobar.prototyp e === undefined ); //true
        println( foobar.__proto_ _ === A.prototype ); //true
        println( foobar.construc tor.prototype === A.prototype ); //true
        println( "--" );
        println( (A.prototype).c onstructor === A ); //true
        println( (A.prototype).p rototype === undefined ); //true
        println( (A.prototype)._ _proto__ === Object.prototyp e ); //true
        println( (A.prototype).c onstructor.prot otype === A.prototype ); //true
        println( "--" );
        println( A.constructor === Function ); //true
        println( A.prototype !== undefined ); //true
        println( A.__proto__ === Function.protot ype ); //true
        println( A.constructor.p rototype === Function.protot ype ); //true
        println( "--" );
        println( foobar instanceof A ); //true
        println( A instanceof Function ); //true
        println( A.prototype instanceof Object ); //true
        ------------------------------------

        there are 3 different objects

        A is a Function object
        A.prototype is an Object object
        foobar is an A object

        each object as its own constructor property pointing to the function who
        created it

        each objects as its own __proto__ property pointing to the
        function.protot ype who created it
        (except if you override the prototype doins something as, A.prototype = new
        B() )

        A is a "special case" because it's a Function object
        so a prototype property is automatically assigned him
        by default this property is a simple Object object

        for hosts implementing __proto__
        you can see __proto__ as the "visible" or "accessible " constructor prototype

        zwetan


        Comment

        • Jonas Raoni

          #5
          Re: Question about making a property on custom object

          Sam Kong escreveu:[color=blue]
          > I have a further question.
          > function C(){
          > this.name = "Test"
          > }
          >
          > function D(){
          > }
          > D.prototype = new C
          >
          > var obj = new D
          > obj.name = "Test2" //HERE, I HAVE A QUESTION.
          >
          > At the last line, does it add a new slot for the property or does it
          > modify the value of existing property 'name'?[/color]

          If you really need such information, you should read the spec, anyway I
          think I doesn't modify anything, since JavaScript has a garbage
          collector... It may create a hash for the "name" property, look for it
          in a list, if not found, it's added, then it receives the reference to
          the value, as the previous reference to the previous object is lost, it
          may be garbage collected.


          --
          Jonas Raoni Soares Silva


          Comment

          • Jonas Raoni

            #6
            Re: Question about making a property on custom object

            Sam Kong escreveu:[color=blue]
            > I have a further question.
            > function C(){
            > this.name = "Test"
            > }
            >
            > function D(){
            > }
            > D.prototype = new C
            >
            > var obj = new D
            > obj.name = "Test2" //HERE, I HAVE A QUESTION.
            >
            > At the last line, does it add a new slot for the property or does it
            > modify the value of existing property 'name'?[/color]

            If you really need such information, you should read the spec, anyway I
            think It doesn't modify anything, since JavaScript has a garbage
            collector... It may create a hash for the "name" property, look for it
            in a list, if not found, it's added, then it receives the reference to
            the value, as the previous reference to the previous object is lost, it
            may be garbage collected.


            --
            Jonas Raoni Soares Silva


            Comment

            • zwetan

              #7
              Re: Question about making a property on custom object


              "Sam Kong" wrote:
              [snip][color=blue]
              >
              > var obj = new D
              > obj.name = "Test2" //HERE, I HAVE A QUESTION.
              >
              > function C(){
              > this.name = "Test"
              > }
              >
              > function D(){
              > }
              > D.prototype = new C
              >
              > var obj = new D
              > obj.name = "Test2"
              >
              > At the last line, does it add a new slot for the property or does it
              > modify the value of existing property 'name'?
              >[/color]

              it add a new slot

              any member defined as a property of an instance
              explicitly override any inherited by delegation member


              function A(){
              }

              A.prototype.tes t = "hello";

              A.prototype.bla h = function(){
              return "[" + this.test + "]";
              }

              foo = new A();
              foo.test = "bonjour";
              foo.blah = function(){
              return "{" + this.test + "}";
              }

              bar = newA();

              println( A.prototype.tes t ); //"hello"
              println( foo.test ); //"bonjour"
              println( foo.blah() ); //"{bonjour}"
              println( bar.test ); //"hello"
              println( bar.blah() ); //"[hello]"


              zwetan












              Comment

              • Sam Kong

                #8
                Re: Question about making a property on custom object

                Wow, zwetan.
                Your explanation is so amazing.
                You surely mastered JavaScript, I guess...

                zwetan wrote:[color=blue]
                > Hello,
                >
                > "Sam Kong" wrote:[color=green]
                > >
                > > I got recently intrigued with JavaScript's prototype-based
                > > object-orientation.
                > > However, I still don't understand the mechanism clearly.
                > >
                > > [Q1]
                > > What's the difference between the following two?
                > >
                > > (1)
                > > function C(){
                > > this.name = "Unknown"
                > > }
                > >
                > > (2)
                > > function C(){
                > > }
                > > C.prototype.nam e = "Unknown"
                > >[/color]
                >
                > when you will instanciate an object
                >
                > foobar = new C();
                >
                > with (1) the property "name" will be explicitly copied into the instance
                >
                > with (2) the property "name" will be inherited by delegation
                > meaning the instance "foobar" does not have a copy of the property "name"
                > but can access it following the prototype chain
                >
                > if you create 10 instances
                > wiht (1) you have 10 different "name" properties
                > with (2) the "name" property is shared by every instances[/color]

                One more question here.

                (1)
                function C(){
                this.f = function(){...}
                }

                (2)
                function my_f(){...}

                function C(){
                this.f = my_f
                }

                In (2), does the method assignment copy function itself, or does it
                just copy function reference?
                I guess, in (1), every object of C will have its own function and in
                (2) there's only one function and it will be shared. Am I right?

                And the best way would be...

                (3)
                function my_f(){...}
                function C(){
                }
                C.prototype.f = my_f()

                Right?
                [color=blue]
                >[color=green]
                > >
                > > [Q2]
                > > There's no notion of Class in JavaScript and everything is an object.[/color]
                >
                > no but you have notion of constructors which can "emulate" classes
                >
                > cf ECMA-262 4.2.1
                > "ECMAScript does not contain proper classes such as those in C++, Smalltalk,
                > or Java, but rather, supports constructors which create objects by executing
                > code that allocates storage for the objects and initialises all or part of
                > them by assigning initial values to their properties. All constructors are
                > objects, but not all objects are constructors. Each constructor has a
                > Prototype property that is used to implement prototype-based inheritance and
                > shared properties. Objects are created by using constructors in new
                > expressions; for example, new String("A String") creates a new String
                > object. Invoking a constructor without using new has consequences that
                > depend on the constructor. For example, String("A String") produces a
                > primitive string, not an object."
                >
                > see http://www.ecma-international.org/pu...s/Ecma-262.htm
                >[color=green]
                > > How many objects are created in the following code including the
                > > objects implicitly created in the behind?
                > >
                > > function C(){
                > > }
                > >
                > > function D(){
                > > }
                > > D.prototype = new C
                > >
                > > var obj = new D
                > >[/color]
                >
                > for the segment of code above
                >
                > 4 if you consider the creation of a prototype property as
                > not-an-object-instanciation
                >
                > function are objects, once you declare one you create an object
                > when you use the "new" keyword you instanciate an object
                >
                > 5 if you consider that the creation of the prototype property is an object
                > instanciation
                >
                > function C in the behind automatically define a "prototype" property
                > which is equivalent to
                > C.prototype = Function.protot ype;[/color]

                I didn't consider this case....
                [color=blue]
                >
                > see ECMA-262 13.2 Creating Function Object
                > "
                > [...]
                > 4. Set the [[Prototype]] property of F to the original Function prototype
                > object as specified in section 15.3.3.1.
                > [...]
                > 9. Create a new object as would be constructed by the expression new
                > Object().
                >
                > 10. Set the constructor property of Result(9) to F. This property is given
                > attributes { DontEnum }.
                >
                > 11. Set the prototype property of F to Result(9). This property is given
                > attributes as specified in section 15.3.5.2.
                > [...]
                > NOTE A prototype property is automatically created for every function,
                > to allow for the possibility that the function will be used as a
                > constructor.
                > "
                >
                > and
                >
                >
                >
                >
                > just writing
                > function C() {
                > }
                >
                > DO create
                > C.prototype = new Object();
                >
                >[color=green]
                > > [Q3]
                > > I saw some codes like "this.base = SomeClass".
                > > When is it needed?
                > > Is it different from ClassName.proto type = new ParentClassName ?
                > >[/color]
                >
                > could you provide some code constructs ?
                >
                > I will try to "guess"...[/color]

                Your guess is correct in every aspect.
                [color=blue]
                >
                > usually when you want to inherit a constructor
                >
                > you can do
                >
                > function A(){
                > }
                >
                > function B(){
                > }
                >
                > B.prototype = new A();
                >
                > but doing that you override the original B "prototype" property
                > and so you override also the "constructo r" property contained in "prototype"
                >
                > foo = new A();
                > //foo.constructor == A
                >
                > bar = new B();
                > //bar.constructor == A, and not B
                >
                > to correct this behaviour you can reassign the constructor property after
                > overriding the prototype
                >
                > function B(){
                > }
                >
                > B.prototype = new A();
                > B.prototype.con structor = B;
                >
                > so now when you instanciate an objet with the B constructor function
                >
                > bar = new B();
                > //bar.constructor == B
                >
                >
                > for the "this.base = SomeClass".
                > I suppose you seen that in that context to emulate superClass constructor
                > call
                >
                > function A( x ){
                > this.x = x;
                > }
                >
                > function B( x, y ){
                > this.base = A;
                > this.base( x );
                > this.y = y;
                > }
                >
                > B.prototype = new A();
                >
                > in this case "this.base" allow to execute A constructor inside the B
                > constructor
                > but with the B function scope, so the "x" is created in the context of B and
                > not A
                >
                > alternatively you can also do that
                >
                > function B( x, y ){
                > A.call( this, x ); // equivalent to "super( x )"
                > this.y = y;
                > }
                >
                > B.prototype = new A();
                >
                >[color=green]
                > > [Q4]
                > > What's the difference between prototype and __proto__?
                > >[/color]
                >
                > first let's define a context
                >
                > function A(){
                > }
                >
                > foobar = new A();
                >
                > in the context of "foobar"
                > foobar.prototyp e does NOT exist
                > foobar.construc tor is a pointer to A constructor function (hence the name)
                > foobar.__proto_ _ is a pointer to A.prototype object
                >
                > in the context of "A"
                > A.prototype is an instancied object
                > (see above "9. Create a new object as would be constructed by the expression
                > new Object().")
                >
                > here what we obtain with JSDB (www.jsdb.org)
                > ------------------------------------
                > function A()
                > {
                >
                > }
                >
                >
                > foobar = new A();
                >
                > println( foobar.construc tor === A ); //true
                > println( foobar.prototyp e === undefined ); //true
                > println( foobar.__proto_ _ === A.prototype ); //true
                > println( foobar.construc tor.prototype === A.prototype ); //true
                > println( "--" );
                > println( (A.prototype).c onstructor === A ); //true
                > println( (A.prototype).p rototype === undefined ); //true
                > println( (A.prototype)._ _proto__ === Object.prototyp e ); //true
                > println( (A.prototype).c onstructor.prot otype === A.prototype ); //true
                > println( "--" );
                > println( A.constructor === Function ); //true
                > println( A.prototype !== undefined ); //true
                > println( A.__proto__ === Function.protot ype ); //true
                > println( A.constructor.p rototype === Function.protot ype ); //true
                > println( "--" );
                > println( foobar instanceof A ); //true
                > println( A instanceof Function ); //true
                > println( A.prototype instanceof Object ); //true
                > ------------------------------------
                >
                > there are 3 different objects
                >
                > A is a Function object
                > A.prototype is an Object object
                > foobar is an A object
                >
                > each object as its own constructor property pointing to the function who
                > created it
                >
                > each objects as its own __proto__ property pointing to the
                > function.protot ype who created it
                > (except if you override the prototype doins something as, A.prototype = new
                > B() )
                >
                > A is a "special case" because it's a Function object
                > so a prototype property is automatically assigned him
                > by default this property is a simple Object object
                >
                > for hosts implementing __proto__
                > you can see __proto__ as the "visible" or "accessible " constructor prototype
                >
                > zwetan[/color]

                It will take me some time to understand what you explained.

                I've been developing web sites for years and I used only JavaScript's
                basic functions (just calling functions, not object-oriented).
                I'm a big fan of Ruby and some ruby guys directed me to Io language
                which is a prototype-based language.
                I found out that JavaScript is also a prototype-based language and is
                very powerful than I thought.
                I decided to study JavaScript more.

                Now I think JavaScript is very consistent and logical, simple but
                powerful and flexible.
                I may use JavaScript for general solutions as well as web client
                script.

                Thanks for your great explanation.

                Sam

                Comment

                • Jonas Raoni

                  #9
                  Re: Question about making a property on custom object

                  Sam Kong escreveu:[color=blue]
                  > zwetan wrote:[color=green]
                  > > "Sam Kong" wrote:[/color]
                  > Wow, zwetan.
                  > Your explanation is so amazing.
                  > You surely mastered JavaScript, I guess...[/color]

                  lol, there are a lot of people with a great knowledge of this language
                  here, maybe because it's simple and fast to learn :)
                  [color=blue]
                  > (1)
                  > function C(){ this.f = function(){...} }
                  >
                  > (2)
                  > function my_f(){...}
                  > function C(){ this.f = my_f }
                  >
                  > In (2), does the method assignment copy function itself, or does it
                  > just copy function reference?[/color]

                  Reference...

                  Everything is passed by reference, but primitive values, like: true,
                  123 or "abc"... But if you create them as objects (new Boolean, new
                  String...), they will be passed by reference too.
                  [color=blue]
                  > I guess, in (1), every object of C will have its own function and in
                  > (2) there's only one function and it will be shared. Am I right?[/color]

                  Yeah :)
                  [color=blue]
                  > And the best way would be...
                  >
                  > (3)
                  > function my_f(){...}
                  > function C(){
                  > }
                  > C.prototype.f = my_f()
                  >
                  > Right?[/color]

                  Right, but if you're not going to share the function "my_f", I preffer
                  an anonymous one:

                  C.prototype.f = function(){};

                  I won't read the rest of the message, It's quite long haha ;]


                  --
                  Jonas Raoni Soares Silva


                  Comment

                  • Thomas 'PointedEars' Lahn

                    #10
                    Re: Question about making a property on custom object

                    Sam Kong wrote:
                    [color=blue]
                    > Thomas,
                    >
                    > Thank you for the answers.[/color]

                    You're welcome.
                    [color=blue]
                    > They are very impressive and helpful.[/color]

                    Thanks, too.
                    [color=blue]
                    > [...]
                    >
                    > function C(){
                    > this.name = "Test"[/color]
                    ^
                    Most statements, especially simple assignments, should be ended with
                    a semicolon to avoid undesired side-effects with automatic semicolon
                    insertion by the script engine.
                    [color=blue]
                    > }
                    >
                    > function D(){
                    > }
                    > D.prototype = new C
                    >
                    > var obj = new D
                    > obj.name = "Test2" //HERE, I HAVE A QUESTION.[/color]

                    Please do not SHOUT on Usenet.
                    [color=blue]
                    > function C(){
                    > this.name = "Test"
                    > }
                    >
                    > function D(){
                    > }
                    > D.prototype = new C
                    >
                    > var obj = new D
                    > obj.name = "Test2"
                    >
                    > At the last line, does it add a new slot for the property or does it
                    > modify the value of existing property 'name'?[/color]

                    It depends on how you interpret "object has property":

                    If you choose to say that objects have all properties, including those
                    that they merely inherit from other objects through the prototype chain,
                    then the last line merely modifies an existing property value.

                    If you choose to say instead that objects have only those properties that
                    they own (called "local properties" in the JavaScript documentation; not
                    to be confused with local variables), the object is added a new (local)
                    property which supersedes the inherited property value as long as it exists
                    local property exists because if it exists, the prototype chain is unused
                    for that accessing the property of that name.

                    You can think of an inherited property value as a default value for a
                    property provided by the prototype, one that can be restored when you
                    delete the local property with the same name (that is, apply the `delete'
                    operator on that property:

                    delete obj.name;
                    alert(obj.name) ; // "Test", as inherited from D.prototype

                    Note that if you do not call C() in D() with the object to be created as
                    the calling object -- that is, either

                    function D()
                    {
                    C.call(this, ...);
                    }

                    or

                    function D()
                    {
                    C.apply(this, ...);
                    }

                    or, if none of the above is available,

                    function D()
                    {
                    this.base = C; // you can use any unused name for this property
                    this.base(...);
                    }

                    -- as it is in your code, the inheritance implementation is not complete.
                    Lasse R. Nielsen has provided code here that shows the respective
                    side-effect:

                    news:u0ybgfdr.f sf@hotpop.com
                    or
                    <URL:http://groups.google.d e/group/comp.lang.javas cript/browse_thread/thread/93e3f206994a1bf/8a59bba12a022e1 a?lnk=st&q=prot otype+push+auth or%3Anielsen+gr oup%3Acomp.lang .javascript&rnu m=4&hl=de#8a59b ba12a022e1a>

                    Please consult the available documentation and do practice tests before
                    you ask further basic questions here. <URL:http://jibbering.com/faq/>


                    PointedEars

                    Comment

                    • Thomas 'PointedEars' Lahn

                      #11
                      Re: Question about making a property on custom object

                      Sam Kong wrote:
                      [color=blue]
                      > Wow, zwetan.
                      > Your explanation is so amazing.
                      > You surely mastered JavaScript, I guess...[/color]

                      Guess again.
                      [color=blue]
                      > zwetan wrote:[color=green]
                      >> "Sam Kong" wrote:[color=darkred]
                      >> >
                      >> > I got recently intrigued with JavaScript's prototype-based
                      >> > object-orientation.
                      >> > However, I still don't understand the mechanism clearly.
                      >> >
                      >> > [Q1]
                      >> > What's the difference between the following two?
                      >> >
                      >> > (1)
                      >> > function C(){
                      >> > this.name = "Unknown"
                      >> > }
                      >> >
                      >> > (2)
                      >> > function C(){
                      >> > }
                      >> > C.prototype.nam e = "Unknown"
                      >> >[/color]
                      >>
                      >> when you will instanciate an object[/color][/color]

                      The verb is `instantiate' and it does not really apply to prototype-based
                      object-oriented programming. Objects are not instances of, and do not
                      inherit from, classes there, but they inherit from other objects. The
                      terms `instance' and `instantiate' are misleading; (to) create and (to)
                      inherit are not.
                      [color=blue][color=green]
                      >> foobar = new C();
                      >>
                      >> with (1) the property "name" will be explicitly copied into the instance[/color][/color]

                      Rubbish. The object that is about to be created (and is eventually created)
                      is added a new property with the primitive string value "Unknown" as value.
                      Nothing is copied from anywhere to anywhere.
                      [color=blue][color=green]
                      >> with (2) the property "name" will be inherited by delegation[/color][/color]

                      Rubbish. The property is inherited through the prototype chain, because if
                      it does not own the property, the lookup proceeds along the prototype
                      chain. When there is an object in the prototype chain that has a property
                      with the accessed name, the reference evaluates to its value. If there is
                      no such object then the reference evaluates to `undefined' when used
                      right-hand side.
                      [color=blue][color=green]
                      >> meaning the instance "foobar" does not have a copy of the property "name"[/color][/color]

                      Again, foobar is not an instance, and nothing is copied.
                      [color=blue][color=green]
                      >> but can access it following the prototype chain[/color][/color]

                      True.
                      [color=blue][color=green]
                      >> if you create 10 instances
                      >> wiht (1) you have 10 different "name" properties
                      >> with (2) the "name" property is shared by every instances[/color][/color]

                      Only if the "instance" (better: object) does not own a property of this name
                      itself.
                      [color=blue]
                      > One more question here.
                      >
                      > (1)
                      > function C(){
                      > this.f = function(){...}
                      > }
                      >
                      > (2)
                      > function my_f(){...}
                      >
                      > function C(){
                      > this.f = my_f
                      > }
                      >
                      > In (2), does the method assignment copy function itself, or does it
                      > just copy function reference?[/color]

                      Nothing is copied. All C objects will have a property f (unless it is
                      deleted after constructing) that is/stores a reference to the Function
                      object referred to by my_f:

                      C_object.f --------> Function object <-------- my_f
                      [color=blue]
                      > I guess, in (1), every object of C will have its own function and in
                      > (2) there's only one function and it will be shared. Am I right?[/color]

                      In a sense. Of course you can still supersede the property for any
                      C object without affecting the same property of other C objects.
                      [color=blue]
                      > And the best way would be...
                      >
                      > (3)
                      > function my_f(){...}
                      > function C(){
                      > }
                      > C.prototype.f = my_f()
                      >
                      > Right?[/color]

                      Whether it is the best way or not depends on its application. Using a
                      prototype method "prevents" you from creating methods on initialization
                      that use arguments the constructor is called with, using closures for
                      example. (Of course you can make use of that feature anyway, superseding
                      the inherited method, hence the quotation marks.)
                      [color=blue][color=green][color=darkred]
                      >> >
                      >> > [Q2]
                      >> > There's no notion of Class in JavaScript and everything is an object.[/color]
                      >>
                      >> no but you have notion of constructors which can "emulate" classes[/color][/color]

                      If you (zwetan) had read _and_ understood what you quoted, you would have
                      recognized that this is not true either. There is much more to class-based
                      inheritance than just an interface to provide properties common to all
                      objects created through it.
                      [color=blue][color=green]
                      >> see http://www.ecma-international.org/pu...s/Ecma-262.htm
                      >>[color=darkred]
                      >> > How many objects are created in the following code including the
                      >> > objects implicitly created in the behind?
                      >> >
                      >> > function C(){
                      >> > }
                      >> >
                      >> > function D(){
                      >> > }
                      >> > D.prototype = new C
                      >> >
                      >> > var obj = new D
                      >> >[/color]
                      >>
                      >> for the segment of code above
                      >>
                      >> 4 if you consider the creation of a prototype property as
                      >> not-an-object-instanciation[/color][/color]

                      It is not at all "an-object-instanciation".
                      [color=blue][color=green]
                      >> function C in the behind automatically define a "prototype" property
                      >> which is equivalent to
                      >> C.prototype = Function.protot ype;[/color]
                      >
                      > I didn't consider this case....[/color]

                      There was nothing to consider. It is as it is.
                      [color=blue][color=green]
                      >>
                      >> see ECMA-262 13.2 Creating Function Object
                      >> "[...][/color][/color]

                      Citing more from what you (zwetan) do not have a minimum clue about?
                      [color=blue][color=green]
                      >> just writing
                      >> function C() {
                      >> }
                      >>
                      >> DO create
                      >> C.prototype = new Object();[/color][/color]

                      Wrong.

                      new Object().constr uctor === Object
                      C.prototype.con structor === C // without prototype overwrite

                      Which is why it is necessary to restore the `constructor' property if you
                      overwrote the default prototype object and need the `constructor' property
                      afterwards. As was described (by zwetan) after that line, BTW.


                      PointedEars

                      Comment

                      • Thomas 'PointedEars' Lahn

                        #12
                        Re: Question about making a property on custom object

                        Thomas 'PointedEars' Lahn wrote:
                        [color=blue]
                        > Sam Kong wrote:[color=green][color=darkred]
                        >>> when you will instanciate an object[/color][/color]
                        >
                        > The verb is `instantiate' and it does not really apply to prototype-based
                        > object-oriented programming. Objects are not instances of, and do not
                        > inherit from, classes there, but they inherit from other objects. The
                        > terms `instance' and `instantiate' are misleading[...][/color]

                        in that regard, for there is variable instantiation for example, which does
                        not have anything to do with object inheritance;
                        [color=blue]
                        > (to) create and (to) inherit are not.[/color]

                        Comment

                        • zwetan

                          #13
                          Re: Question about making a property on custom object

                          "Sam Kong" wrote:[color=blue]
                          > Wow, zwetan.
                          > Your explanation is so amazing.
                          > You surely mastered JavaScript, I guess...
                          >[/color]

                          well I just read a lot the ECMA-262 specs, nothing more really

                          but thanks :)

                          by the way I didn't think of it at that time
                          but you can find here
                          Whereas HTML defines a webpage's structure and content and CSS sets the formatting and appearance, JavaScript adds interactivity to a webpage and creates rich web applications.



                          a very good short explanation of the ten years history of JavaScript,
                          why it was designed like that, etc..

                          a must read!


                          [snip][color=blue]
                          >
                          > One more question here.
                          >
                          > (1)
                          > function C(){
                          > this.f = function(){...}
                          > }
                          >
                          > (2)
                          > function my_f(){...}
                          >
                          > function C(){
                          > this.f = my_f
                          > }
                          >
                          > In (2), does the method assignment copy function itself, or does it
                          > just copy function reference?[/color]

                          all objects are copied by reference
                          all primitives are copied by value
                          [color=blue]
                          > I guess, in (1), every object of C will have its own function and in
                          > (2) there's only one function and it will be shared. Am I right?
                          >[/color]

                          not really like that

                          when you declare a function to be used as a constructor

                          function C(){
                          this.p = anything;
                          }

                          foobar = new C();

                          even if anything is copied by reference
                          the property "p" will be explicity copied in the newly instancied objet
                          [color=blue]
                          > And the best way would be...
                          >
                          > (3)
                          > function my_f(){...}
                          > function C(){
                          > }
                          > C.prototype.f = my_f()
                          >
                          > Right?[/color]

                          I personally prefere to declare it this way

                          function C(){
                          }

                          C.prototype.f = function() {...}

                          but it's just a matter of preference

                          the problem with this notation is that I almost never saw
                          any JavaScript editors being able to reckonize this notation

                          except :)

                          JS Eclipse



                          [snip][color=blue]
                          >
                          > It will take me some time to understand what you explained.
                          >[/color]

                          well take your time and really experiment *in* the language
                          best way to learn imho
                          [color=blue]
                          > I've been developing web sites for years and I used only JavaScript's
                          > basic functions (just calling functions, not object-oriented).
                          > I'm a big fan of Ruby and some ruby guys directed me to Io language
                          > which is a prototype-based language.
                          > I found out that JavaScript is also a prototype-based language and is
                          > very powerful than I thought.
                          > I decided to study JavaScript more.
                          >[/color]

                          one good thing to study a language is too see codes already
                          programmed by others perharps more experienced
                          you should check dojo, mochikit, etc..
                          also some libs on JSAN etc.

                          on a smaller level you can also check chunk of my codes
                          if it can help you see how things can be organized


                          another good thing is to study JavaScript outside of the browser
                          to not be poluted by the DOM

                          www.jsdb.org is a perfect tool for that
                          (another tool is KJScmd on Linux)

                          [color=blue]
                          > Now I think JavaScript is very consistent and logical, simple but
                          > powerful and flexible.[/color]

                          same here :)
                          [color=blue]
                          > I may use JavaScript for general solutions as well as web client
                          > script.
                          >[/color]

                          it can be frustrating on the browser with some difference in implementation
                          but you can also experiment with
                          - WSH (Windows Script Host)
                          which can run JScript code as shell script
                          - JSDB
                          a command line tool, but which got also a way to
                          combine the scripts inside the executable and so make little CLI tool
                          - JScript.NET
                          you can perfectly code a full .NET app in JScript.NET
                          etc..
                          [color=blue]
                          > Thanks for your great explanation.
                          >[/color]

                          you're welcome :)

                          zwetan


                          Comment

                          • Sam Kong

                            #14
                            Re: Question about making a property on custom object


                            zwetan wrote:[color=blue]
                            > "Sam Kong" wrote:[color=green]
                            > > Wow, zwetan.
                            > > Your explanation is so amazing.
                            > > You surely mastered JavaScript, I guess...
                            > >[/color]
                            >
                            > well I just read a lot the ECMA-262 specs, nothing more really
                            >
                            > but thanks :)
                            >
                            > by the way I didn't think of it at that time
                            > but you can find here
                            > http://www.mozilla.org/js/language/
                            > http://www.mozilla.org/js/language/ICFP-Keynote.ppt
                            >
                            > a very good short explanation of the ten years history of JavaScript,
                            > why it was designed like that, etc..
                            >
                            > a must read!
                            >
                            >
                            > [snip][color=green]
                            > >
                            > > One more question here.
                            > >
                            > > (1)
                            > > function C(){
                            > > this.f = function(){...}
                            > > }
                            > >
                            > > (2)
                            > > function my_f(){...}
                            > >
                            > > function C(){
                            > > this.f = my_f
                            > > }
                            > >
                            > > In (2), does the method assignment copy function itself, or does it
                            > > just copy function reference?[/color]
                            >
                            > all objects are copied by reference
                            > all primitives are copied by value
                            >[color=green]
                            > > I guess, in (1), every object of C will have its own function and in
                            > > (2) there's only one function and it will be shared. Am I right?
                            > >[/color]
                            >
                            > not really like that
                            >
                            > when you declare a function to be used as a constructor
                            >
                            > function C(){
                            > this.p = anything;
                            > }
                            >
                            > foobar = new C();
                            >
                            > even if anything is copied by reference
                            > the property "p" will be explicity copied in the newly instancied objet
                            >[color=green]
                            > > And the best way would be...
                            > >
                            > > (3)
                            > > function my_f(){...}
                            > > function C(){
                            > > }
                            > > C.prototype.f = my_f()
                            > >
                            > > Right?[/color]
                            >
                            > I personally prefere to declare it this way
                            >
                            > function C(){
                            > }
                            >
                            > C.prototype.f = function() {...}
                            >
                            > but it's just a matter of preference
                            >
                            > the problem with this notation is that I almost never saw
                            > any JavaScript editors being able to reckonize this notation
                            >
                            > except :)
                            >
                            > JS Eclipse
                            > http://www.interaktonline.com/Produc...ipse/Overview/
                            >
                            >
                            > [snip][color=green]
                            > >
                            > > It will take me some time to understand what you explained.
                            > >[/color]
                            >
                            > well take your time and really experiment *in* the language
                            > best way to learn imho
                            >[color=green]
                            > > I've been developing web sites for years and I used only JavaScript's
                            > > basic functions (just calling functions, not object-oriented).
                            > > I'm a big fan of Ruby and some ruby guys directed me to Io language
                            > > which is a prototype-based language.
                            > > I found out that JavaScript is also a prototype-based language and is
                            > > very powerful than I thought.
                            > > I decided to study JavaScript more.
                            > >[/color]
                            >
                            > one good thing to study a language is too see codes already
                            > programmed by others perharps more experienced
                            > you should check dojo, mochikit, etc..
                            > also some libs on JSAN etc.
                            >
                            > on a smaller level you can also check chunk of my codes
                            > if it can help you see how things can be organized
                            > http://www.burrrn.com/projects/
                            >
                            > another good thing is to study JavaScript outside of the browser
                            > to not be poluted by the DOM
                            >
                            > www.jsdb.org is a perfect tool for that
                            > (another tool is KJScmd on Linux)
                            >
                            >[color=green]
                            > > Now I think JavaScript is very consistent and logical, simple but
                            > > powerful and flexible.[/color]
                            >
                            > same here :)
                            >[color=green]
                            > > I may use JavaScript for general solutions as well as web client
                            > > script.
                            > >[/color]
                            >
                            > it can be frustrating on the browser with some difference in implementation
                            > but you can also experiment with
                            > - WSH (Windows Script Host)
                            > which can run JScript code as shell script
                            > - JSDB
                            > a command line tool, but which got also a way to
                            > combine the scripts inside the executable and so make little CLI tool
                            > - JScript.NET
                            > you can perfectly code a full .NET app in JScript.NET
                            > etc..
                            >[color=green]
                            > > Thanks for your great explanation.
                            > >[/color]
                            >
                            > you're welcome :)
                            >
                            > zwetan[/color]

                            Thank you soooo much, zwetan!

                            Sam

                            Comment

                            • Thomas 'PointedEars' Lahn

                              #15
                              Re: Question about making a property on custom object

                              Sam Kong wrote:
                              [color=blue]
                              > zwetan wrote:[color=green]
                              >> "Sam Kong" wrote:[color=darkred]
                              >> > Wow, zwetan.
                              >> > Your explanation is so amazing.
                              >> > You surely mastered JavaScript, I guess...
                              >> >[/color]
                              >>
                              >> well I just read a lot the ECMA-262 specs, nothing more really
                              >>
                              >> but [...][/color][/color]

                              obviously, you have not understood a word of it.
                              [color=blue][color=green][color=darkred]
                              >> > One more question here.
                              >> >
                              >> > (1)
                              >> > function C(){
                              >> > this.f = function(){...}
                              >> > }
                              >> >
                              >> > (2)
                              >> > function my_f(){...}
                              >> >
                              >> > function C(){
                              >> > this.f = my_f
                              >> > }
                              >> >
                              >> > In (2), does the method assignment copy function itself, or does it
                              >> > just copy function reference?[/color]
                              >>
                              >> all objects are copied by reference[/color][/color]

                              Rubbish! References are values. Nothing is copied this way, _especially_
                              not objects!
                              [color=blue][color=green]
                              >> all primitives are copied by value[/color][/color]

                              Primitive values are values. Nothing is copied from anywhere to anywhere!
                              [color=blue][color=green][color=darkred]
                              >> > I guess, in (1), every object of C will have its own function and in
                              >> > (2) there's only one function and it will be shared. Am I right?
                              >> >[/color]
                              >>
                              >> not really like that
                              >>
                              >> when you declare a function to be used as a constructor
                              >>
                              >> function C(){
                              >> this.p = anything;
                              >> }
                              >>
                              >> foobar = new C();
                              >>
                              >> even if anything is copied by reference
                              >> the property "p" will be explicity copied in the newly instancied objet[/color][/color]

                              You really cannot be helped. The voices in your head are more important to
                              you than specified and _provable_ facts. You are hereby nominated for the
                              next VK Award.
                              [color=blue]
                              > Thank you soooo much, zwetan![/color]

                              Do not trust any information from this source. It is utterly wrong.


                              PointedEars

                              Comment

                              Working...