Loading ...
Sorry, an error occurred while loading the content.

Re: [ydn-javascript] Confusing behaviour with YAHOO.lang.extend

Expand Messages
  • Adam Moore
    ... Gerry, this is the expected behavior. Items provided to the overrides parameter are added to the object s prototype. Each instance shares the same
    Message 1 of 3 , Dec 21, 2007
    • 0 Attachment
      On Fri, Dec 21, 2007 at 12:49:08PM -0000, gerryvandermaesen wrote:
      > Hi,
      >
      > I encountered an unexpected behaviour while working with class
      > inheritance.
      >
      > I do the following:
      >
      > // superclass constructor
      > MyClassA = function() {};
      >
      > // subclass constructor
      > MyClassB = function() {
      > MyClassB.superclass.constructor.apply(this, arguments);
      > };
      >
      > // extend
      > YAHOO.lang.extend(MyClassB, MyClassA, { props: { name: "ClassA" } });
      >
      > // create first instance
      > var foo = new MyClassB();
      > alert(foo.props.name); // alerts "ClassA";
      > foo.props.name = "Custom name";
      >
      > // create second instance
      > var bar = new MyClassB();
      > alert(bar.props.name); // alerts "Custom name", I expected "ClassA";
      >
      > The thing I don't understand is why the new instance takes the
      > modified value of a property that is defined in the class' prototype.
      > Is this the expected behaviour? And more importantly, how do I prevent
      > this?

      Gerry, this is the expected behavior. Items provided to the 'overrides'
      parameter are added to the object's prototype. Each instance shares the
      same prototype. Use the 'overrides' parameter to add/override methods,
      not to define state that is specific to an instance. Do that in the
      constructor instead:

      MyClassB = function() {
      MyClassB.superclass.constructor.apply(this, arguments);
      this.props: {
      name: "ClassB"
      };
      };

      -Adam
    Your message has been successfully submitted and would be delivered to recipients shortly.