3

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think I get what you mean here: keys:Object.keys. So Object.keys are actually the Object properties. What does the other '|| keys' do here?
@Thorpe - It's saying if it already has Object.keys (a native browser version), use that, if not then use the keys function defined in that file: github.com/sstephenson/prototype/blob/master/src/prototype/lang/…
I thought so :) I believe that your answer was the best at explaining things. +1
1

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

2 Comments

Hmm... where do I find this line?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.