I believe I understand the difference between extending an "instance"
and extending a "class". If I simply define a javascript method and
attach it to an instance, then I can execute that method ONLY on that
instance. If I attach it to the prototype for the class, then it is
available to ALL instances of the "class" going forward.

So say I have an object X, such as :

function X ( ... ) { ...}
var x = new X( ... );

Orr since we are talking about Prototype, I will use :

var X = Class.create();
X.prototype = {
    initialize: function() { ... },
    someMethod: function() { ... }
};
var x = new X( ... );

So then, if I wanted to attach an instance x of X with a new method, I
would do the following (regardless of whether I used Prototype or
not) :

function newMethod() { ... }
var x = new X( ... );

If I want to attach methods to all instances of X, I would do the
following normally :
X.prototype.newMethod = function ( ...) { ... }

And I would do the following in Prototype :
Object.extend(X.prototype, function newMethod( ... ) { ... });

Hopefully, you are still with me, because I have not asked my question
yet. I see that methods such as sub(), scan(), etc. are added to
String - ALL String instances - by "extending its prototype", i.e.
like this :

Object.extend(String.prototype, {
    ...
    sub : function( ... ) { ... },
    scan : function( ...) { ... },
    ...
});

HOWEVER, I see this tidbit as well :

Object.extend(String, {
    interpret : function ( ... ) { ... } ,
    ...
});

Clearly the above is NOT extending the prototype for String. It also
(seems to me) not extending any particular instance of String. So
what's going on here? The only thing I can surmise is that when you
extend the prototype for an object, you can refer to "this" to access
internal state. And that ability to use "this" will be intact even if
a particular instance of an object was assigned with a method.

While I see in the last example, that "this" is not being referenced
in any methods in question, for a similar example where "Hash" is
being extended instead of "Hash.prototype", "this is indeed being used
in the implementation for toQueryString(), toJSON() on Hash. That
leaves me scratching my head.

So given an object X, what is the difference between the following :
1) Object.extend(X, { ... });
2) Object.extend(X.prototype, { ... });

Thanks in advance for any insight.


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Spinoffs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-spinoffs?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to