2

I'm fairly new to javascript, and I'm studying inheritance. I'm trying to understand the code below, but I don't quite get what lines 3 and 4 are all about. For one thing, why is the child's prototype property being set on line 2 the parent object, only to be set to something else on the following line. And I don't understand the arguments for the call() method. I thought the 1st arg was supposed to be the function context for Array.prototype.slice(). So why is 1 passed in? And the second arg seems to be the arguments object for Function.prototype.extend(). But I thought you needed to use apply() if the arguments to Array.prototype.slice() are in the form of an array. Anyway, I seem to be missing the whole point of this small block of code. Any insights by more experienced programmers would be much appreciated.

Thanks. Mike H

Code snippet comes from: http://www.htmlgoodies.com/html5/javascript/calling-parent-methods-in-javascript.html#fbid=D89pEqSy7xl

Function.prototype.extend = function(parent) {
  var child = this;
  child.prototype = parent;
  child.prototype = new child(Array.prototype.slice.call(1,arguments));
  child.prototype.constructor = child;
} 
jfriend00
  • 683,504
  • 96
  • 985
  • 979
user3538389
  • 51
  • 1
  • 1
  • 2

1 Answers1

0

It looks like the line #3 in the code is with the parameters inverted, but let's try to make things clearer following your questions:

For one thing, why is the child's prototype property being set on line 2 the parent object, only to be set to something else on the following line

It's just holding the child object so it can be instantiated to define the child prototype chain

And I don't understand the arguments for the call() method. I thought the 1st arg was supposed to be the function context for Array.prototype.slice(). So why is 1 passed in? And the second arg seems to be the arguments object for Function.prototype.extend().

If you check this url, you'll see that it takes two arguments, the second being optional: array.slice(begin[, end]); That said, arguments should be the first argument to .call(), as it is the context, as you've already pointed out.

But I thought you needed to use apply() if the arguments to Array.prototype.slice() are in the form of an array.

You're also right about the arguments form, it should be an array. And guess what? It is... :)
Check this http://jsfiddle.net/x52Aa/

Hope I could help you at least with the most.
Cheers

recamilio
  • 89
  • 4
  • Thanks very much to all who took the time to respond to my question. Your help was much appreciated. Sorry for my delayed response. I think I put the wrong email address in, I didn't get a notification about my question. Thanks again. You may have saved my sanity! Mike H. – user3538389 Apr 18 '14 at 16:12