Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #12787 > unrolled thread

Adding new method to existing object

Started bycezary.tomczyk@gmail.com
First post2012-03-16 03:56 -0700
Last post2012-03-18 04:27 -0700
Articles 20 on this page of 23 — 5 participants

Back to article view | Back to comp.lang.javascript


Contents

  Adding new method to existing object cezary.tomczyk@gmail.com - 2012-03-16 03:56 -0700
    Re: Adding new method to existing object David Mark <dmark.cinsoft@gmail.com> - 2012-03-16 04:50 -0700
      Re: Adding new method to existing object Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-03-16 15:31 +0100
        Re: Adding new method to existing object David Mark <dmark.cinsoft@gmail.com> - 2012-03-16 11:51 -0700
          Re: Adding new method to existing object Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-03-17 00:10 +0100
            Re: Adding new method to existing object David Mark <dmark.cinsoft@gmail.com> - 2012-03-16 17:25 -0700
              Re: Adding new method to existing object Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-03-17 02:04 +0100
                Re: Adding new method to existing object David Mark <dmark.cinsoft@gmail.com> - 2012-03-16 18:15 -0700
      Re: Adding new method to existing object cezary.tomczyk@gmail.com - 2012-03-16 10:18 -0700
        Re: Adding new method to existing object David Mark <dmark.cinsoft@gmail.com> - 2012-03-16 11:56 -0700
        Re: Adding new method to existing object David Mark <dmark.cinsoft@gmail.com> - 2012-03-16 13:01 -0700
          Re: Adding new method to existing object cezary.tomczyk@gmail.com - 2012-03-17 04:58 -0700
            Re: Adding new method to existing object David Mark <dmark.cinsoft@gmail.com> - 2012-03-17 16:04 -0700
              Re: Adding new method to existing object cezary.tomczyk@gmail.com - 2012-03-18 04:24 -0700
                Re: Adding new method to existing object John G Harris <john@nospam.demon.co.uk> - 2012-03-18 13:16 +0000
    Re: Adding new method to existing object John G Harris <john@nospam.demon.co.uk> - 2012-03-16 17:09 +0000
      Re: Adding new method to existing object cezary.tomczyk@gmail.com - 2012-03-16 10:46 -0700
    Re: Adding new method to existing object Scott Sauyet <scott.sauyet@gmail.com> - 2012-03-16 13:43 -0700
    Re: Adding new method to existing object Scott Sauyet <scott.sauyet@gmail.com> - 2012-03-16 20:15 -0700
      Re: Adding new method to existing object cezary.tomczyk@gmail.com - 2012-03-17 05:17 -0700
      Re: Adding new method to existing object cezary.tomczyk@gmail.com - 2012-03-17 05:24 -0700
        Re: Adding new method to existing object David Mark <dmark.cinsoft@gmail.com> - 2012-03-17 16:16 -0700
          Re: Adding new method to existing object cezary.tomczyk@gmail.com - 2012-03-18 04:27 -0700

Page 1 of 2  [1] 2  Next page →


#12787 — Adding new method to existing object

Fromcezary.tomczyk@gmail.com
Date2012-03-16 03:56 -0700
SubjectAdding new method to existing object
Message-ID<31786995.22.1331895413978.JavaMail.geo-discussion-forums@vbat19>
Hi,

I want to extend my prototype object using another object. Just created some example code:

http://jsfiddle.net/u9e7R/13/

I tested the addMethod function in Firefox 10,11, Chrome 17 and IE 9. But it will fail in IE8. In IE8 console when I run jsCode().test2(); I see 'Object does not support property or method "test2"'.

addMethod was based on http://alturl.com/4mk6k, but I tried to code some another few methods, for example by creating temp object, copying properties and set new object in prototype object. But this method in IE8 fails too.

Can someone explain me how can I extend existing prototype object using new object?

-- 
Regards,
CT

[toc] | [next] | [standalone]


#12788

FromDavid Mark <dmark.cinsoft@gmail.com>
Date2012-03-16 04:50 -0700
Message-ID<571e5767-fc18-4945-b356-4004af1145e8@q12g2000yqg.googlegroups.com>
In reply to#12787
On Mar 16, 6:56 am, cezary.tomc...@gmail.com wrote:
> Hi,
>
> I want to extend my prototype object using another object. Just created some example code:
>
> http://jsfiddle.net/u9e7R/13/
>
> I tested the addMethod function in Firefox 10,11, Chrome 17 and IE 9. But it will fail in IE8. In IE8 console when I run jsCode().test2(); I see 'Object does not support property or method "test2"'.

You added it too late to have any effect on the constructed object.
Augmenting the prototype property of the constructor won't do anything
until you construct another object.  On the contrary, you hacked the
internal prototype of the constructed object for the other browsers.

What exactly are you trying to accomplish with this?

As a side note, it's hard to believe that JSFiddle still lacks My
Library.  They were supposed to add it ages ago.  All of those old,
dead Dojo, Prototype, etc. versions, yet no reference to the script
they've been trying to catch up to for the last four years. :(

[toc] | [prev] | [next] | [standalone]


#12791

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2012-03-16 15:31 +0100
Message-ID<7404478.9nW1t498yI@PointedEars.de>
In reply to#12788
David Mark wrote:

> On Mar 16, 6:56 am, cezary.tomc...@gmail.com wrote:
>> I want to extend my prototype object using another object. Just created
>> some example code:
>>
>> http://jsfiddle.net/u9e7R/13/
>>
>> I tested the addMethod function in Firefox 10,11, Chrome 17 and IE 9. But
>> it will fail in IE8. In IE8 console when I run jsCode().test2(); I see
>> 'Object does not support property or method "test2"'.
> 
> You added it too late to have any effect on the constructed object.
> Augmenting the prototype property of the constructor won't do anything
> until you construct another object.

Although the explanation might hold some truth for this situation (I had no 
time to check yet), in itself it is utter nonsense.  A property is resolved 
against the prototype chain only on property access.  Therefore, if you 
augment the prototype of the constructor of an object, that affects all 
objects created with that constructor (no matter the current value of the 
`constructor' property), no matter when they have been constructed.  It is 
why augmenting `Object.prototype', no matter where in the program, can be 
that harmful to program flow if appropriate precautions have not been taken.

There is no difference between ECMAScript implementations there.

  function Constructor() {}

  var obj = new Constructor();

  Constructor.prototype.answer = 42;

  /* 42 */
  console.log(obj.answer);


PointedEars
-- 
When all you know is jQuery, every problem looks $(olvable).

[toc] | [prev] | [next] | [standalone]


#12821

FromDavid Mark <dmark.cinsoft@gmail.com>
Date2012-03-16 11:51 -0700
Message-ID<ee3d3a2a-9711-425a-a151-cba30d66b41f@g16g2000yqe.googlegroups.com>
In reply to#12791
On Mar 16, 10:31 am, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
> David Mark wrote:
> > On Mar 16, 6:56 am, cezary.tomc...@gmail.com wrote:
> >> I want to extend my prototype object using another object. Just created
> >> some example code:
>
> >>http://jsfiddle.net/u9e7R/13/
>
> >> I tested the addMethod function in Firefox 10,11, Chrome 17 and IE 9. But
> >> it will fail in IE8. In IE8 console when I run jsCode().test2(); I see
> >> 'Object does not support property or method "test2"'.
>
> > You added it too late to have any effect on the constructed object.
> > Augmenting the prototype property of the constructor won't do anything
> > until you construct another object.
>
> Although the explanation might hold some truth for this situation (I had no
> time to check yet), in itself it is utter nonsense.

Strong words, indeed. You may be right, I've been up around the clock
wrapping up a project.

> A property is resolved
> against the prototype chain only on property access.

Yes.  And calling a method on an object applies.

> Therefore, if you
> augment the prototype of the constructor of an object, that affects all
> objects created with that constructor (no matter the current value of the
> `constructor' property), no matter when they have been constructed.

I was mistaken; I don't use the constructor property for much of
anything (it's pretty useless). *If* that property hasn't been stomped
on at some point, it references the function used to construct the
object. I had it in my head that the prototype property of that object
references an object that was copied *once* and put at the head of the
prototype chain on constructing the object. From what you are saying,
it isn't copied but referenced where it sits.

> It is
> why augmenting `Object.prototype', no matter where in the program, can be
> that harmful to program flow if appropriate precautions have not been taken.

I don't do that under any circumstances. :)

>
> There is no difference between ECMAScript implementations there.
>
>   function Constructor() {}
>
>   var obj = new Constructor();
>
>   Constructor.prototype.answer = 42;
>
>   /* 42 */
>   console.log(obj.answer);

Yes, I see that works; so clearly I was wrong. Regardless, that's an
execrable pattern and certainly not one that I would use. Any project
that did something like that would be re-factored long before I ran it
for the first time. :)

Ah, right.  This works too:-

function Constructor() { Constructor.prototype.answer = 42; }
  var obj = new Constructor();

  /* 42 */
  console.log(obj.answer);

I was thinking of *replacing* the prototype object, rather than
augmenting it. Never made the distinction as I try not to think about
things I would never do (or would let stand if somebody else did it).

[toc] | [prev] | [next] | [standalone]


#12832

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2012-03-17 00:10 +0100
Message-ID<1795217.bUTGlsRvRN@PointedEars.de>
In reply to#12821
David Mark wrote:

> Thomas 'PointedEars' Lahn wrote:
>> A property is resolved against the prototype chain only on property
>> access.
> 
> Yes.  And calling a method on an object applies.

Exactly.

>> Therefore, if you augment the prototype of the constructor of an object,
>> that affects all objects created with that constructor (no matter the
>> current value of the `constructor' property), no matter when they have
>> been constructed.
> 
> I was mistaken; I don't use the constructor property for much of
> anything (it's pretty useless). *If* that property hasn't been stomped
> on at some point, it references the function used to construct the
> object. I had it in my head that the prototype property of that object
> references an object that was copied *once* and put at the head of the
> prototype chain on constructing the object. From what you are saying,
> it isn't copied but referenced where it sits.

Yes, as it is the case with ECMAScript implementations most of the time 
(always with this property).

>> It is why augmenting `Object.prototype', no matter where in the program,
>> can be that harmful to program flow if appropriate precautions have not
>> been taken.
> 
> I don't do that under any circumstances. :)

Certainly a good idea until ECMAScript Edition 5 has been widely adopted, 
where one can define properties as not enumerable, for example:

  Object.defineProperty(Object.prototype, "foo", {
    value: 42,
    writable: true
  });

(The defaults are value === undefined, enumerable === false, writable === 
false, configurable === false, i.e.

  Object.defineProperty(Object.prototype, "foo", {});

creates a not enumerable, "eternally" frozen property on the Object 
prototype object with value `undefined'.  In that sense,

  Object.defineProperty(Object.prototype, "answer", {value: 42});

would be the ultimate achievement ;-))

>> There is no difference between ECMAScript implementations there.
>>
>> function Constructor() {}
>>
>> var obj = new Constructor();
>>
>> Constructor.prototype.answer = 42;
>>
>> /* 42 */
>> console.log(obj.answer);
> 
> Yes, I see that works; so clearly I was wrong. Regardless, that's an
> execrable pattern and certainly not one that I would use. Any project
> that did something like that would be re-factored long before I ran it
> for the first time. :)

It is a potentially useful pattern if you consider that primitive values are 
internally converted to corresponding objects if they are used in a 
/MemberExpression/.  For example, I can see no harm in writing

  String.prototype.htmlEscape = function () {
    return this.replace(/[\u0080-\uFFFF]/g, function (m) {
      return "&#" + m.charCodeAt(0) + ";";
    });
  };

  console.log("|@#°½¬¦¢øĸjħŋđδ".htmlEscape());

  /* optional */
  delete String.prototype.htmlEscape;

instead of

  var htmlEscape = function (s) {
    return s.replace(/[\u0080-\uFFFF]/g, function (m) {
      return "&#" + m.charCodeAt(0) + ";";
    });
  };

  console.log(htmlEscape("|@#°½¬¦¢øĸjħŋđδ"));

The advantage of augmenting built-in prototype objects is that if the new 
property is callable, you can use in the method all the properties in the 
prototype chain without having to use another wrapper explicitly.  The 
disadvantage is that name of the custom property might clash with built-in 
property names, and that (in implementations of ECMAScript before Edition 5) 
they must show up in for-in iteration.

> Ah, right.  This works too:-
> 
> function Constructor() { Constructor.prototype.answer = 42; }
>   var obj = new Constructor();
> 
>   /* 42 */
>   console.log(obj.answer);
> 
> I was thinking of *replacing* the prototype object, rather than
> augmenting it. Never made the distinction as I try not to think about
> things I would never do (or would let stand if somebody else did it).

That example shows an approach for another potentially useful pattern, too, 
where prototype methods close over arguments or local variables, creating 
"private properties" accessible by inheritable "protected methods":

  function Constructor (answer)
  {
    Constructor.prototype.getAnswer = function () {
      return answer;
    };
  }

  var obj = new Constructor();

  /* 42 */
  obj.getAnswer();  

(The reduced memory efficiency can be mitigated with slightly reduced 
runtime efficiency if the property is tested before the function is created 
and a reference to it assigned, so that this only happen twice if someone 
has messed with the prototype in the meantime.)

There is another way to do a similar thing, though (quite clever, not my 
idea):

  function Constructor () {}

  Constructor.prototype = (function () {
    var privatePrototypeProperty = 42;

    return {
      constructor: Constructor,

      prototypeMethod: function () {
        return privatePrototypeProperty;
      }
    };
  }());

  var obj = new Constructor();

  /* 42 */
  obj.prototypeMethod();  

The difference is that the second "private property" is prototype-based, 
while the first one is instance-based.


PointedEars
-- 
var bugRiddenCrashPronePieceOfJunk = (
    navigator.userAgent.indexOf('MSIE 5') != -1
    && navigator.userAgent.indexOf('Mac') != -1
)  // Plone, register_function.js:16

[toc] | [prev] | [next] | [standalone]


#12836

FromDavid Mark <dmark.cinsoft@gmail.com>
Date2012-03-16 17:25 -0700
Message-ID<d4454218-f394-4bba-8b0f-6e1e17ea2281@2g2000yqk.googlegroups.com>
In reply to#12832
On Mar 16, 7:10 pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
> David Mark wrote:
> > Thomas 'PointedEars' Lahn wrote:
> >> A property is resolved against the prototype chain only on property
> >> access.
>
> > Yes.  And calling a method on an object applies.
>
> Exactly.
>
> >> Therefore, if you augment the prototype of the constructor of an object,
> >> that affects all objects created with that constructor (no matter the
> >> current value of the `constructor' property), no matter when they have
> >> been constructed.
>
> > I was mistaken; I don't use the constructor property for much of
> > anything (it's pretty useless). *If* that property hasn't been stomped
> > on at some point, it references the function used to construct the
> > object. I had it in my head that the prototype property of that object
> > references an object that was copied *once* and put at the head of the
> > prototype chain on constructing the object. From what you are saying,
> > it isn't copied but referenced where it sits.
>
> Yes, as it is the case with ECMAScript implementations most of the time
> (always with this property).
>
> >> It is why augmenting `Object.prototype', no matter where in the program,
> >> can be that harmful to program flow if appropriate precautions have not
> >> been taken.
>
> > I don't do that under any circumstances. :)
>
> Certainly a good idea until ECMAScript Edition 5 has been widely adopted,
> where one can define properties as not enumerable, for example:
>
>   Object.defineProperty(Object.prototype, "foo", {
>     value: 42,
>     writable: true
>   });
>
> (The defaults are value === undefined, enumerable === false, writable ===
> false, configurable === false, i.e.
>
>   Object.defineProperty(Object.prototype, "foo", {});
>
> creates a not enumerable, "eternally" frozen property on the Object
> prototype object with value `undefined'.  In that sense,
>
>   Object.defineProperty(Object.prototype, "answer", {value: 42});
>
> would be the ultimate achievement ;-))
>
> >> There is no difference between ECMAScript implementations there.
>
> >> function Constructor() {}
>
> >> var obj = new Constructor();
>
> >> Constructor.prototype.answer = 42;
>
> >> /* 42 */
> >> console.log(obj.answer);
>
> > Yes, I see that works; so clearly I was wrong. Regardless, that's an
> > execrable pattern and certainly not one that I would use. Any project
> > that did something like that would be re-factored long before I ran it
> > for the first time. :)
>
> It is a potentially useful pattern if you consider that primitive values are
> internally converted to corresponding objects if they are used in a
> /MemberExpression/.  For example, I can see no harm in writing
>
>   String.prototype.htmlEscape = function () {
>     return this.replace(/[\u0080-\uFFFF]/g, function (m) {
>       return "&#" + m.charCodeAt(0) + ";";
>     });
>   };
>
>   console.log("|@#°½¬¦¢øĸjħŋđδ".htmlEscape());
>
>   /* optional */
>   delete String.prototype.htmlEscape;
>
> instead of
>
>   var htmlEscape = function (s) {
>     return s.replace(/[\u0080-\uFFFF]/g, function (m) {
>       return "&#" + m.charCodeAt(0) + ";";
>     });
>   };
>
>   console.log(htmlEscape("|@#°½¬¦¢øĸjħŋđδ"));

I meant the bit where the prototype is augmented after constructing
objects (not to mention the way it was done in this case!) :(

>
> The advantage of augmenting built-in prototype objects is that if the new
> property is callable, you can use in the method all the properties in the
> prototype chain without having to use another wrapper explicitly.  The
> disadvantage is that name of the custom property might clash with built-in
> property names, and that (in implementations of ECMAScript before Edition 5)
> they must show up in for-in iteration.

Yes, I know. :)

>
> > Ah, right.  This works too:-
>
> > function Constructor() { Constructor.prototype.answer = 42; }
> >   var obj = new Constructor();
>
> >   /* 42 */
> >   console.log(obj.answer);
>
> > I was thinking of *replacing* the prototype object, rather than
> > augmenting it. Never made the distinction as I try not to think about
> > things I would never do (or would let stand if somebody else did it).
>
> That example shows an approach for another potentially useful pattern, too,
> where prototype methods close over arguments or local variables, creating
> "private properties" accessible by inheritable "protected methods":
>
>   function Constructor (answer)
>   {
>     Constructor.prototype.getAnswer = function () {
>       return answer;
>     };
>   }
>
>   var obj = new Constructor();
>
>   /* 42 */
>   obj.getAnswer();
>
> (The reduced memory efficiency can be mitigated with slightly reduced
> runtime efficiency if the property is tested before the function is created
> and a reference to it assigned, so that this only happen twice if someone
> has messed with the prototype in the meantime.)
>
> There is another way to do a similar thing, though (quite clever, not my
> idea):
>
>   function Constructor () {}
>
>   Constructor.prototype = (function () {
>     var privatePrototypeProperty = 42;
>
>     return {
>       constructor: Constructor,
>
>       prototypeMethod: function () {
>         return privatePrototypeProperty;
>       }
>     };
>   }());
>
>   var obj = new Constructor();
>
>   /* 42 */
>   obj.prototypeMethod();
>
> The difference is that the second "private property" is prototype-based,
> while the first one is instance-based.
>

Yes, I use a variations of the latter a lot, though not quite as
compartmentalized as that. Richard once had a page that described
several different variations on this theme. If that's where you got
this and the page is still up, please send me a link as it was a
useful resource.

[toc] | [prev] | [next] | [standalone]


#12837

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2012-03-17 02:04 +0100
Message-ID<2919534.8F1xFLJzEo@PointedEars.de>
In reply to#12836
David Mark wrote:

> On Mar 16, 7:10 pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
> wrote:
>> David Mark wrote:
>> > Thomas 'PointedEars' Lahn wrote:
>> >> function Constructor() {}
>> >> 
>> >> var obj = new Constructor();
>> >> 
>> >> Constructor.prototype.answer = 42;
>> >> 
>> >> /* 42 */
>> >> console.log(obj.answer);
>> > 
>> > Yes, I see that works; so clearly I was wrong. Regardless, that's an
>> > execrable pattern and certainly not one that I would use. Any project
>> > that did something like that would be re-factored long before I ran it
>> > for the first time. :)
>>
>> It is a potentially useful pattern if you consider that primitive values
>> are internally converted to corresponding objects if they are used in a
>> /MemberExpression/.  For example, I can see no harm in writing
>>
>> String.prototype.htmlEscape = function () {
>> return this.replace(/[\u0080-\uFFFF]/g, function (m) {
>> return "&#" + m.charCodeAt(0) + ";";
>> });
>> };
>>
>> console.log("|@#°½¬¦¢øĸjħŋđδ".htmlEscape());
>>
>> /* optional */
>> delete String.prototype.htmlEscape;
>>
>> instead of
>>
>> var htmlEscape = function (s) {
>> return s.replace(/[\u0080-\uFFFF]/g, function (m) {
>> return "&#" + m.charCodeAt(0) + ";";
>> });
>> };
>>
>> console.log(htmlEscape("|@#°½¬¦¢øĸjħŋđδ"));
> 
> I meant the bit where the prototype is augmented after constructing
> objects (not to mention the way it was done in this case!) :(

`String' refers to a `Function' instance.  "…" is converted to a `String' 
instance (as if by `new String("…")' in a /MemberExpression/.  I do not see 
your point, and I can see no reason for dismay.

I also see no reason for a full quote.  That you are removing quote marks 
(`>') from "empty" lines on top of that is disturbing, as it makes reading 
quoted quotes considerably harder (the reason for quote marks: one mark for 
each *level*, *no matter* if the original line was empty).

> Yes, I use a variations of the latter a lot, though not quite as
> compartmentalized as that. Richard once had a page that described
> several different variations on this theme. If that's where you got
> this and the page is still up, please send me a link as it was a
> useful resource.

I was posting from memory.  I do not know who had that idea.

-- 
When all you know is jQuery, every problem looks $(olvable).

[toc] | [prev] | [next] | [standalone]


#12838

FromDavid Mark <dmark.cinsoft@gmail.com>
Date2012-03-16 18:15 -0700
Message-ID<1aab69f3-75d4-47d8-9279-2d9a01d33108@g16g2000yqe.googlegroups.com>
In reply to#12837
On Mar 16, 9:04 pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
> David Mark wrote:
> > On Mar 16, 7:10 pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
> > wrote:
> >> David Mark wrote:
> >> > Thomas 'PointedEars' Lahn wrote:
> >> >> function Constructor() {}
>
> >> >> var obj = new Constructor();
>
> >> >> Constructor.prototype.answer = 42;
>
> >> >> /* 42 */
> >> >> console.log(obj.answer);
>
> >> > Yes, I see that works; so clearly I was wrong. Regardless, that's an
> >> > execrable pattern and certainly not one that I would use. Any project
> >> > that did something like that would be re-factored long before I ran it
> >> > for the first time. :)
>
> >> It is a potentially useful pattern if you consider that primitive values
> >> are internally converted to corresponding objects if they are used in a
> >> /MemberExpression/.  For example, I can see no harm in writing
>
> >> String.prototype.htmlEscape = function () {
> >> return this.replace(/[\u0080-\uFFFF]/g, function (m) {
> >> return "&#" + m.charCodeAt(0) + ";";
> >> });
> >> };
>
> >> console.log("|@#°½¬¦¢øĸjħŋđδ".htmlEscape());
>
> >> /* optional */
> >> delete String.prototype.htmlEscape;
>
> >> instead of
>
> >> var htmlEscape = function (s) {
> >> return s.replace(/[\u0080-\uFFFF]/g, function (m) {
> >> return "&#" + m.charCodeAt(0) + ";";
> >> });
> >> };
>
> >> console.log(htmlEscape("|@#°½¬¦¢øĸjħŋđδ"));
>
> > I meant the bit where the prototype is augmented after constructing
> > objects (not to mention the way it was done in this case!) :(
>
> `String' refers to a `Function' instance.  "…" is converted to a `String'
> instance (as if by `new String("…")' in a /MemberExpression/.  I do not see
> your point, and I can see no reason for dismay.

I was referring to the OP's example.

>
> I also see no reason for a full quote.  That you are removing quote marks
> (`>') from "empty" lines on top of that is disturbing, as it makes reading
> quoted quotes considerably harder (the reason for quote marks: one mark for
> each *level*, *no matter* if the original line was empty).

I didn't do anything to the quote marks. Blame GG.

[toc] | [prev] | [next] | [standalone]


#12805

Fromcezary.tomczyk@gmail.com
Date2012-03-16 10:18 -0700
Message-ID<10224075.1379.1331918290476.JavaMail.geo-discussion-forums@yniz5>
In reply to#12788
W dniu piątek, 16 marca 2012, 12:50:39 UTC+1 użytkownik David Mark napisał:
> On Mar 16, 6:56 am, cezary.tomc...@gmail.com wrote:
> > Hi,
> >
> > I want to extend my prototype object using another object. Just created some example code:
> >
> > http://jsfiddle.net/u9e7R/13/
> >
> > I tested the addMethod function in Firefox 10,11, Chrome 17 and IE 9. But it will fail in IE8. In IE8 console when I run jsCode().test2(); I see 'Object does not support property or method "test2"'.
> 
> You added it too late to have any effect on the constructed object.
> Augmenting the prototype property of the constructor won't do anything
> until you construct another object.  On the contrary, you hacked the
> internal prototype of the constructed object for the other browsers.
> 
> What exactly are you trying to accomplish with this?

I try to extend my jsCode object by adding another objects to object jsCode. Exactly to jsCode prototype to use inheritance. I just want to create jsCode and implement method chaining. If I described it correctly.

> As a side note, it's hard to believe that JSFiddle still lacks My
> Library.  They were supposed to add it ages ago.  All of those old,
> dead Dojo, Prototype, etc. versions, yet no reference to the script
> they've been trying to catch up to for the last four years. :(

BTW as for MyLibrary I use the library in my private projects :-)
BTW When Your book will be released?

-- 
Regards,
CT

[toc] | [prev] | [next] | [standalone]


#12823

FromDavid Mark <dmark.cinsoft@gmail.com>
Date2012-03-16 11:56 -0700
Message-ID<5efba3c8-5005-4c35-8455-ff470addfbb2@m13g2000yqc.googlegroups.com>
In reply to#12805
On Mar 16, 1:18 pm, cezary.tomc...@gmail.com wrote:
> W dniu piątek, 16 marca 2012, 12:50:39 UTC+1 użytkownik David Mark napisał:
>
> > On Mar 16, 6:56 am, cezary.tomc...@gmail.com wrote:
> > > Hi,
>
> > > I want to extend my prototype object using another object. Just created some example code:
>
> > >http://jsfiddle.net/u9e7R/13/
>
> > > I tested the addMethod function in Firefox 10,11, Chrome 17 and IE 9. But it will fail in IE8. In IE8 console when I run jsCode().test2(); I see 'Object does not support property or method "test2"'.
>
> > You added it too late to have any effect on the constructed object.
> > Augmenting the prototype property of the constructor won't do anything
> > until you construct another object.  On the contrary, you hacked the
> > internal prototype of the constructed object for the other browsers.
>
> > What exactly are you trying to accomplish with this?
>
> I try to extend my jsCode object by adding another objects to object jsCode. Exactly to jsCode prototype to use inheritance. I just want to create jsCode and implement method chaining. If I described it correctly.

I'm going to have to re-review what you did when I am fresher.

>
> > As a side note, it's hard to believe that JSFiddle still lacks My
> > Library.  They were supposed to add it ages ago.  All of those old,
> > dead Dojo, Prototype, etc. versions, yet no reference to the script
> > they've been trying to catch up to for the last four years. :(
>
> BTW as for MyLibrary I use the library in my private projects :-)

Cool!

> BTW When Your book will be released?

Whenever I finish writing it; been too busy the last few months. It
has several OO examples, expanding on the "inherit" API function, but
none that rely on prototypes augmented *after* constructing objects.

[toc] | [prev] | [next] | [standalone]


#12828

FromDavid Mark <dmark.cinsoft@gmail.com>
Date2012-03-16 13:01 -0700
Message-ID<694b2fe2-7b9f-4e17-87bf-76ce8969d947@p13g2000yqd.googlegroups.com>
In reply to#12805
On Mar 16, 1:18 pm, cezary.tomc...@gmail.com wrote:
> W dniu piątek, 16 marca 2012, 12:50:39 UTC+1 użytkownik David Mark napisał:
>
> > On Mar 16, 6:56 am, cezary.tomc...@gmail.com wrote:
> > > Hi,
>
> > > I want to extend my prototype object using another object. Just created some example code:
>
> > >http://jsfiddle.net/u9e7R/13/
>
> > > I tested the addMethod function in Firefox 10,11, Chrome 17 and IE 9. But it will fail in IE8. In IE8 console when I run jsCode().test2(); I see 'Object does not support property or method "test2"'.
>
> > You added it too late to have any effect on the constructed object.
> > Augmenting the prototype property of the constructor won't do anything
> > until you construct another object.  On the contrary, you hacked the
> > internal prototype of the constructed object for the other browsers.
>
> > What exactly are you trying to accomplish with this?
>
> I try to extend my jsCode object by adding another objects to object jsCode.

As mentioned, this is vague.

I yanked out your other (presumably) working forks, which simplifies
things quite a bit, the problem should jump off the page:-

var global = this;

if (typeof global.jsCode == 'undefined')
{
    global.jsCode = {};
}

(function( global, doc )
{
    var jsCode = function( params )
    {
        return new jsCode.init( params );
    };

    jsCode.init = function( params )
    {
        return this;
    };

    jsCode.init.prototype =
    {
        constructor: jsCode,

// You stepped on the constructor property. I assume this was
intentional, but the next method fails to take this into account.

        getPrototypeObject : function( object )
        {

                    // return object.constructor.prototype

                    return jsCode.init.prototype;

// See the difference?

        },

        test : function()
        {
            console.log('Function test complete');
            return this;
        },

        addMethod : function (name, fn)
        {
            var object = this.getPrototypeObject( this );

            // Save a reference to the old method
            var old = object[ name ];

            // Overwrite the method with our new one
            object[ name ] = function()
            {
                // Check the number of incoming arguments,
                // compared to our overloaded function
                if ( fn.length == arguments.length )
                {
                    // If there was a match, run the function
                    return fn.apply( this, arguments );
                }
                // Otherwise, fallback to the old method
                else if ( typeof old === "function" )
                {
                    return old.apply( this, arguments );
                }
            };
        }

    };

    // Expose jsCode to the global object
    global.jsCode = jsCode;

})( global, document );

var test2 = function()
{
    console.log('Function test2 complete');
    return this;
};

jsCode().addMethod('test2', test2);
console.log('test')
console.log( jsCode() );

jsCode().test2().test();​

> Exactly to jsCode prototype to use inheritance. I just want to create jsCode and implement method chaining. If I described it correctly.
>

It's going to need some more explanation; it looks unnecessarily
complicated to me.  Why would a constructor function need an "init"
method?  Reminds me of the old Prototypejs library (not a good thing).

[toc] | [prev] | [next] | [standalone]


#12845

Fromcezary.tomczyk@gmail.com
Date2012-03-17 04:58 -0700
Message-ID<16476250.1111.1331985481075.JavaMail.geo-discussion-forums@vbiz13>
In reply to#12828
W dniu piątek, 16 marca 2012, 21:01:20 UTC+1 użytkownik David Mark napisał:
> On Mar 16, 1:18 pm, cezary.tomc...@gmail.com wrote:
> > W dniu piątek, 16 marca 2012, 12:50:39 UTC+1 użytkownik David Mark napisał:
> >
> > > On Mar 16, 6:56 am, cezary.tomc...@gmail.com wrote:
> > > > Hi,
> >
> > > > I want to extend my prototype object using another object. Just created some example code:
> >
> > > >http://jsfiddle.net/u9e7R/13/
> >
> > > > I tested the addMethod function in Firefox 10,11, Chrome 17 and IE 9. But it will fail in IE8. In IE8 console when I run jsCode().test2(); I see 'Object does not support property or method "test2"'.
> >
> > > You added it too late to have any effect on the constructed object.
> > > Augmenting the prototype property of the constructor won't do anything
> > > until you construct another object.  On the contrary, you hacked the
> > > internal prototype of the constructed object for the other browsers.
> >
> > > What exactly are you trying to accomplish with this?
> >
> > I try to extend my jsCode object by adding another objects to object jsCode.
> 
> As mentioned, this is vague.
> 
> I yanked out your other (presumably) working forks, which simplifies
> things quite a bit, the problem should jump off the page:-
> 
> var global = this;
> 
> if (typeof global.jsCode == 'undefined')
> {
>     global.jsCode = {};
> }
> 
> (function( global, doc )
> {
>     var jsCode = function( params )
>     {
>         return new jsCode.init( params );
>     };
> 
>     jsCode.init = function( params )
>     {
>         return this;
>     };
> 
>     jsCode.init.prototype =
>     {
>         constructor: jsCode,
> 
> // You stepped on the constructor property. I assume this was
> intentional, but the next method fails to take this into account.

Hm, I belive that I was read somewhere about seeting constructor in prototype. But I see that this is not needed. As I understand constructor returns a reference to the Object function that created the instance's prototype. So, I do not have to set this again in my case. I'm right?

>         getPrototypeObject : function( object )
>         {
> 
>                     // return object.constructor.prototype
> 
>                     return jsCode.init.prototype;
> 
> // See the difference?

Yes. In my case it is enought to return object jsCode.init.prototype;

>         },
> 
>         test : function()
>         {
>             console.log('Function test complete');
>             return this;
>         },
> 
>         addMethod : function (name, fn)
>         {
>             var object = this.getPrototypeObject( this );
> 
>             // Save a reference to the old method
>             var old = object[ name ];
> 
>             // Overwrite the method with our new one
>             object[ name ] = function()
>             {
>                 // Check the number of incoming arguments,
>                 // compared to our overloaded function
>                 if ( fn.length == arguments.length )
>                 {
>                     // If there was a match, run the function
>                     return fn.apply( this, arguments );
>                 }
>                 // Otherwise, fallback to the old method
>                 else if ( typeof old === "function" )
>                 {
>                     return old.apply( this, arguments );
>                 }
>             };
>         }
> 
>     };
> 
>     // Expose jsCode to the global object
>     global.jsCode = jsCode;
> 
> })( global, document );
> 
> var test2 = function()
> {
>     console.log('Function test2 complete');
>     return this;
> };
> 
> jsCode().addMethod('test2', test2);
> console.log('test')
> console.log( jsCode() );
> 
> jsCode().test2().test();​
> 
> > Exactly to jsCode prototype to use inheritance. I just want to create jsCode and implement method chaining. If I described it correctly.
> >
> 
> It's going to need some more explanation; it looks unnecessarily
> complicated to me.  Why would a constructor function need an "init"
> method?  Reminds me of the old Prototypejs library (not a good thing).

I want to create an object jsCode and add then some methods. Like in, for example, PHP where I have classes and can extend them by another methods. In my case the jsCode is a object, have a "bulit-in" methods and can be "extended" by another methods (like a extensions or plugin, somethings line that).

I just want to implement chained method calls and don't want to use new operator every time. That's why I use the new operator and create an instance of a jsCode object. Maybe this way is not good practice.

Finally I want to use every method like this: jsCode().method1().method2().methodX();

Of course, some methods will return this object, some not.

-- 
Regards,
CT

[toc] | [prev] | [next] | [standalone]


#12860

FromDavid Mark <dmark.cinsoft@gmail.com>
Date2012-03-17 16:04 -0700
Message-ID<f0fc1577-700f-418e-9f45-28aa5c36eea2@q18g2000yqh.googlegroups.com>
In reply to#12845
On Mar 17, 7:58 am, cezary.tomc...@gmail.com wrote:
> W dniu piątek, 16 marca 2012, 21:01:20 UTC+1 użytkownik David Mark napisał:
>
>
>
>
>
>
>
>
>
> > On Mar 16, 1:18 pm, cezary.tomc...@gmail.com wrote:
> > > W dniu piątek, 16 marca 2012, 12:50:39 UTC+1 użytkownik David Mark napisał:
>
> > > > On Mar 16, 6:56 am, cezary.tomc...@gmail.com wrote:
> > > > > Hi,
>
> > > > > I want to extend my prototype object using another object. Just created some example code:
>
> > > > >http://jsfiddle.net/u9e7R/13/
>
> > > > > I tested the addMethod function in Firefox 10,11, Chrome 17 and IE 9. But it will fail in IE8. In IE8 console when I run jsCode().test2(); I see 'Object does not support property or method "test2"'.
>
> > > > You added it too late to have any effect on the constructed object.
> > > > Augmenting the prototype property of the constructor won't do anything
> > > > until you construct another object.  On the contrary, you hacked the
> > > > internal prototype of the constructed object for the other browsers.
>
> > > > What exactly are you trying to accomplish with this?
>
> > > I try to extend my jsCode object by adding another objects to object jsCode.
>
> > As mentioned, this is vague.
>
> > I yanked out your other (presumably) working forks, which simplifies
> > things quite a bit, the problem should jump off the page:-
>
> > var global = this;
>
> > if (typeof global.jsCode == 'undefined')
> > {
> >     global.jsCode = {};
> > }
>
> > (function( global, doc )
> > {
> >     var jsCode = function( params )
> >     {
> >         return new jsCode.init( params );
> >     };
>
> >     jsCode.init = function( params )
> >     {
> >         return this;
> >     };
>
> >     jsCode.init.prototype =
> >     {
> >         constructor: jsCode,
>
> > // You stepped on the constructor property. I assume this was
> > intentional, but the next method fails to take this into account.
>
> Hm, I belive that I was read somewhere about seeting constructor in prototype. But I see that this is not needed. As I understand constructor returns a reference to the Object function that created the instance's prototype. So, I do not have to set this again in my case. I'm right?

You replaced the object referenced by the prototype property of your
constructor, so if you want to make use of the constructor property,
you will have to supply a reference to the constructor.  As it sits,
you supplied a reference to another function.


>
> >         getPrototypeObject : function( object )
> >         {
>
> >                     // return object.constructor.prototype
>
> >                     return jsCode.init.prototype;
>
> > // See the difference?
>
> Yes. In my case it is enought to return object jsCode.init.prototype;
>
>
>
>
>
>
>
>
>
> >         },
>
> >         test : function()
> >         {
> >             console.log('Function test complete');
> >             return this;
> >         },
>
> >         addMethod : function (name, fn)
> >         {
> >             var object = this.getPrototypeObject( this );
>
> >             // Save a reference to the old method
> >             var old = object[ name ];
>
> >             // Overwrite the method with our new one
> >             object[ name ] = function()
> >             {
> >                 // Check the number of incoming arguments,
> >                 // compared to our overloaded function
> >                 if ( fn.length == arguments.length )
> >                 {
> >                     // If there was a match, run the function
> >                     return fn.apply( this, arguments );
> >                 }
> >                 // Otherwise, fallback to the old method
> >                 else if ( typeof old === "function" )
> >                 {
> >                     return old.apply( this, arguments );
> >                 }
> >             };
> >         }
>
> >     };
>
> >     // Expose jsCode to the global object
> >     global.jsCode = jsCode;
>
> > })( global, document );
>
> > var test2 = function()
> > {
> >     console.log('Function test2 complete');
> >     return this;
> > };
>
> > jsCode().addMethod('test2', test2);
> > console.log('test')
> > console.log( jsCode() );
>
> > jsCode().test2().test();​
>
> > > Exactly to jsCode prototype to use inheritance. I just want to create jsCode and implement method chaining. If I described it correctly.
>
> > It's going to need some more explanation; it looks unnecessarily
> > complicated to me.  Why would a constructor function need an "init"
> > method?  Reminds me of the old Prototypejs library (not a good thing).
>
> I want to create an object jsCode and add then some methods. Like in, for example, PHP where I have classes and can extend them by another methods. In my case the jsCode is a object, have a "bulit-in" methods and can be "extended" by another methods (like a extensions or plugin, somethings line that).
>
> I just want to implement chained method calls and don't want to use new operator every time. That's why I use the new operator and create an instance of a jsCode object. Maybe this way is not good practice.
>
> Finally I want to use every method like this: jsCode().method1().method2().methodX();

Did you have a look at the OO wrappers for My Library?  They are
pretty trivial and do everything you are trying to accomplish.

>
> Of course, some methods will return this object, some not.

Certainly.  Making every method "chainable" would be downright
inconvenient as functions often need to communicate back to the caller
(e.g. returning the value of a property).

[toc] | [prev] | [next] | [standalone]


#12875

Fromcezary.tomczyk@gmail.com
Date2012-03-18 04:24 -0700
Message-ID<5407668.3681.1332069852998.JavaMail.geo-discussion-forums@ynmb12>
In reply to#12860
W dniu niedziela, 18 marca 2012, 00:04:08 UTC+1 użytkownik David Mark napisał:
> On Mar 17, 7:58 am, cezary.tomc...@gmail.com wrote:
> > W dniu piątek, 16 marca 2012, 21:01:20 UTC+1 użytkownik David Mark napisał:
[...]
> > Hm, I belive that I was read somewhere about seeting constructor in prototype. But I see that this is not needed. As I understand constructor returns a reference to the Object function that created the instance's prototype. So, I do not have to set this again in my case. I'm right?

> You replaced the object referenced by the prototype property of your
> constructor, so if you want to make use of the constructor property,
> you will have to supply a reference to the constructor.  As it sits,
> you supplied a reference to another function.

Ah see my mistake now.

There are so many articles about OO JavaScript programming and sometimes can be everything mix up :-)

[...]

> > Finally I want to use every method like this: jsCode().method1().method2().methodX();
> 
> Did you have a look at the OO wrappers for My Library?  They are
> pretty trivial and do everything you are trying to accomplish.

Yes. I know that MyLibrary is OO. That's why I look out there :-) But not everything is clear for me. For example the inherit function I tried to understand how this method works and adapt to my example. It did not work me. So I wanted to do something new, step by step to understand the exact object oriented JavaScript.

> > Of course, some methods will return this object, some not.
> 
> Certainly.  Making every method "chainable" would be downright
> inconvenient as functions often need to communicate back to the caller
> (e.g. returning the value of a property).

Yes. Agree.

-- 
Regards,
CT

[toc] | [prev] | [next] | [standalone]


#12881

FromJohn G Harris <john@nospam.demon.co.uk>
Date2012-03-18 13:16 +0000
Message-ID<9dcQgAEmAeZPFwoq@J.A830F0FF37FB96852AD08924D9443D28E23ED5CD>
In reply to#12875
On Sun, 18 Mar 2012 at 04:24:12, in comp.lang.javascript,  wrote:

  <snip>
>There are so many articles about OO JavaScript programming and
>sometimes can be everything mix up :-)
  <snip>

I've seen a video where the inventor of SmallTalk says that if a
language hasn't got *all* the features of SmallTalk then it isn't OO. So
by that criterion your scheme isn't OO.

On the other hand, I think that ECMAScript is OO already. It has
objects, the objects have inheritance, and programmers are oriented
towards them. Why add code complications to do it a different way?

*Really* why?

  John
-- 
John Harris

[toc] | [prev] | [next] | [standalone]


#12803

FromJohn G Harris <john@nospam.demon.co.uk>
Date2012-03-16 17:09 +0000
Message-ID<BfVPuQHjP3YPFwXE@J.A830F0FF37FB96852AD08924D9443D28E23ED5CD>
In reply to#12787
On Fri, 16 Mar 2012 at 03:56:53, in comp.lang.javascript,  wrote:

  <snip>
>Can someone explain me how can I extend existing prototype object using
>new object?

  Thing.prototype.blobby = new WhatsIt();

Or did you mean

  Thing.prototype = new Thing(a, b, c);

In general, what do you mean by 'extend', and do you want to create a
new type of object or a modified current type? You didn't say.

  John
-- 
John Harris

[toc] | [prev] | [next] | [standalone]


#12808

Fromcezary.tomczyk@gmail.com
Date2012-03-16 10:46 -0700
Message-ID<7596121.1342.1331919963571.JavaMail.geo-discussion-forums@vbtv42>
In reply to#12803
W dniu piątek, 16 marca 2012, 18:09:55 UTC+1 użytkownik John G Harris napisał:
> On Fri, 16 Mar 2012 at 03:56:53, in comp.lang.javascript,  wrote:
> 
>   <snip>
> >Can someone explain me how can I extend existing prototype object using
> >new object?
> 
>   Thing.prototype.blobby = new WhatsIt();
> 
> Or did you mean
> 
>   Thing.prototype = new Thing(a, b, c);
> 
> In general, what do you mean by 'extend', and do you want to create a
> new type of object or a modified current type? You didn't say.

'Extend' I mean create a new type of object (usually function) and then add that to existing object.

-- 
Regards,
CT

[toc] | [prev] | [next] | [standalone]


#12830

FromScott Sauyet <scott.sauyet@gmail.com>
Date2012-03-16 13:43 -0700
Message-ID<0ec4f134-5a6c-4bf5-88cd-19d641dc135f@q11g2000vbu.googlegroups.com>
In reply to#12787
CT wrote:
> I want to extend my prototype object using another object. Just created some example code:
>
> http://jsfiddle.net/u9e7R/13/
> [ ... ]
> Can someone explain me how can I extend existing prototype object using new object?

The following is a fairly minimal fix to what you did:

    <http://jsfiddle.net/u9e7R/16/>

I renamed the constructor to have a InitialCapital letter (just a
convention, but a pretty strong one).  I removed the init function.
The rest pretty much stands as it was, including the fairly bizarre
method of using an instance to attach properties to the prototype.

If I find some time this evening, I'll write up an alternative
implementation.

  -- Scott

[toc] | [prev] | [next] | [standalone]


#12842

FromScott Sauyet <scott.sauyet@gmail.com>
Date2012-03-16 20:15 -0700
Message-ID<fe0320ca-41db-425e-8be2-dcec3878b903@v2g2000vbx.googlegroups.com>
In reply to#12787
CT wrote:
> I want to extend my prototype object using another object. Just created some example code:
>
> http://jsfiddle.net/u9e7R/13/
>
> Can someone explain me how can I extend existing prototype object using new object?

David Mark pointed out the basic flaw in your code, that you munged
the constructor.  I posted a fairly minimal fix to that earlier.  (I
apologize for posting only a link; I know that's poor citizenship on
USENET.  I was in a hurry, but that's no excuse.)  But that version is
to me still fundamentally flawed.  It's far too complicated for what
it does.  Below is another version with nearly the same behavior, but
significantly simpler code.

There are two main differences in behavior: first, there is no factory
function, just the plain constructor; and second, the addMethod
function is attached to the constructor, not to the instances.  To me
that simply makes sense, since it is updating the prototype.  If you
meant this to apply to instances, the code would be far more simple.

Here is the simplified code, also available at <http://jsfiddle.net/
u9e7R/18/>


    //~ I just attach this to the global namespace here instead
    //~ of using the `global` variable to reference `this`.

    var JsCode = (function() {
      var JsCode = function(params) {
      };

      //~ Could use your technique of assigning the prototype,
      //~ but I don't see the point.  I just refer to it directly.
      var proto = JsCode.prototype;

      proto.test = function() {
        console.log('Function test complete');
        return this;
      };

      //~ Since this is added to the prototype, there is no
      //~ need for a function to find the prototype of the object.
      JsCode.addMethod = function (name, fn) {
        var old = proto[name];

        proto[name] = function() {
          if ( fn.length == arguments.length ) {
            return fn.apply( this, arguments );
          } else if ( typeof old === "function" ) {
            // really need error checking here.
            return old.apply( this, arguments );
          }
        };
      };

      return JsCode;

    })();

    var test2 = function() {
      console.log('Function test2 complete');
      return this;
    };

    JsCode.addMethod('test2', test2);

    //~ Without the factory function, you must use `new`.
    var jsc = new JsCode();
    jsc.test2();  //~ or chain these as in the original
    jsc.test();


This does change the interface a little, but seems much cleaner.  If
you really want a factory function, you could replace the `return`
statement above with something like this:

    var result = function(params) {
      return new JsCode(params);
    }
    result.addMethod = JsCode.addMethod;
    return result;

(although that could be further simplified if desired.)

Does this capture the essence of what you're trying to do?

  -- Scott

[toc] | [prev] | [next] | [standalone]


#12846

Fromcezary.tomczyk@gmail.com
Date2012-03-17 05:17 -0700
Message-ID<23935524.6.1331986626075.JavaMail.geo-discussion-forums@vbla14>
In reply to#12842
W dniu sobota, 17 marca 2012, 04:15:52 UTC+1 użytkownik Scott Sauyet napisał:
> CT wrote:
> > I want to extend my prototype object using another object. Just created some example code:
> >
> > http://jsfiddle.net/u9e7R/13/
> >
> > Can someone explain me how can I extend existing prototype object using new object?
> 
> David Mark pointed out the basic flaw in your code, that you munged
> the constructor.  I posted a fairly minimal fix to that earlier.  (I
> apologize for posting only a link; I know that's poor citizenship on
> USENET.  I was in a hurry, but that's no excuse.)  But that version is
> to me still fundamentally flawed.  It's far too complicated for what
> it does.  Below is another version with nearly the same behavior, but
> significantly simpler code.
> 
> There are two main differences in behavior: first, there is no factory
> function, just the plain constructor; and second, the addMethod
> function is attached to the constructor, not to the instances.  To me
> that simply makes sense, since it is updating the prototype.  If you
> meant this to apply to instances, the code would be far more simple.
> 
> Here is the simplified code, also available at <http://jsfiddle.net/
> u9e7R/18/>

It's simpler, like I've done this before, but not on the jsFiddle. Next I just wanted to return an instance of an object.

>     //~ I just attach this to the global namespace here instead
>     //~ of using the `global` variable to reference `this`.
> 
>     var JsCode = (function() {
>       var JsCode = function(params) {
>       };
> 
>       //~ Could use your technique of assigning the prototype,
>       //~ but I don't see the point.  I just refer to it directly.
>       var proto = JsCode.prototype;
> 
>       proto.test = function() {
>         console.log('Function test complete');
>         return this;
>       };
> 
>       //~ Since this is added to the prototype, there is no
>       //~ need for a function to find the prototype of the object.
>       JsCode.addMethod = function (name, fn) {
>         var old = proto[name];
> 
>         proto[name] = function() {
>           if ( fn.length == arguments.length ) {
>             return fn.apply( this, arguments );
>           } else if ( typeof old === "function" ) {
>             // really need error checking here.
>             return old.apply( this, arguments );
>           }
>         };
>       };
> 
>       return JsCode;
> 
>     })();
> 
>     var test2 = function() {
>       console.log('Function test2 complete');
>       return this;
>     };
> 
>     JsCode.addMethod('test2', test2);
> 
>     //~ Without the factory function, you must use `new`.
>     var jsc = new JsCode();
>     jsc.test2();  //~ or chain these as in the original
>     jsc.test();
> 
> 
> This does change the interface a little, but seems much cleaner.  If
> you really want a factory function, you could replace the `return`
> statement above with something like this:
> 
>     var result = function(params) {
>       return new JsCode(params);
>     }
>     result.addMethod = JsCode.addMethod;
>     return result;
> 
> (although that could be further simplified if desired.)
> 
> Does this capture the essence of what you're trying to do?

Yes! Thank You for clarifying me. This is exactly what I wanted to achieve.

-- 
Regards,
CT

[toc] | [prev] | [next] | [standalone]


Page 1 of 2  [1] 2  Next page →

Back to top | Article view | comp.lang.javascript


csiph-web