Teej
Teej

Reputation: 12873

How does Prototype extend Objects?

I've been reading up on the Prototype source code while learning Javascript. I've been wondering where is the code that is being used to extend Native Objects.

I've been seeing,

Object.extend(Function.prototype, (function() {
Object.extend(String.prototype, (function() {
Object.extend(Number.prototype, (function() {

all over the place and I can't find where the .extend function is coming from.

I've seen this:

  function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
  }

at line 194-198 and wonder if this is the one. I can't find out how it is, if it is.

anyway, my question as I stated above is how/where does Prototype extend the Native objects.

Upvotes: 3

Views: 2354

Answers (2)

Jacob Relkin
Jacob Relkin

Reputation: 163258

If you look at the source code here:
https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/object.js you will see this:

alt text

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630429

Yes, it is the function you're seeing, later in the code you'll see it used to get Object.extend, like this:

extend(Object, {
    extend: extend, //here's where the magic gets added
    inspect: inspect,
    toJSON: NATIVE_JSON_STRINGIFY_SUPPORT ? stringify : toJSON,
    toQueryString: toQueryString,
    toHTML: toHTML,
    keys: Object.keys || keys,
    values: values,
    clone: clone,
    isElement: isElement,
    isArray: isArray,
    isHash: isHash,
    isFunction: isFunction,
    isString: isString,
    isNumber: isNumber,
    isDate: isDate,
    isUndefined: isUndefined
});

So it's calling extend() with itself as a property to add to theObject prototype, adding itself as the .extend method on Object.

Upvotes: 3

Related Questions