3

Every function-constructor in JS has a prototype.constructor property. And it stores the definition of the function:

function Rabbit(value) {
    this.jumps: value;
}
alert(Rabbit.prototype.constructor);  // alerts exactly the definition of the Rabbit function

Now I check a simple function, not a function-constructor, it doesn't have any this in the body:

function bar(val) {
    alert(val);
}
alert(bar.prototype.constructor);   // behavior is absolutely the same: it alerts the definition of bar

Now I check built-in Array() function:

alert(Array.prototype.constructor);  // in Chrome it alerts "function Array() { [native code] }"

And now I want to check some built-in function of a built-in object:

// The error is thrown in console: TypeError: Cannot read property 'constructor' of undefined 

alert(Array.prototype.sort.prototype.constructor);

sort doesn't have prototype. Where is it? And where is its constructor?

Green
  • 28,742
  • 61
  • 158
  • 247
  • uhh ... that first example is a syntax error; should be `this.jumps = value;`. All functions are constructors, or can be called as constructors, whether or not they contain references to `this`. – Pointy Sep 19 '12 at 15:28
  • 2
    I suspect that the `sort()` function has no prototype because it's a native method. – Pointy Sep 19 '12 at 15:30
  • 1
    "Where is its constructor"... `Array.prototype.sort.constructor` – James Allardice Sep 19 '12 at 15:30
  • @James Allardice, right, and its constructor is `function Function() { [native code] }`, now I see. Is it because there is nothing higher in the chain of prototypes of this built in function? – Green Sep 19 '12 at 15:37

1 Answers1

1

If you add the method yourself it returns what you expect:

    Array.prototype.remove= function(){
        var what, a= arguments, L= a.length, ax;
        while(L && this.length){
            what= a[--L];
            while((ax= this.indexOf(what))!= -1) this.splice(ax, 1);
        }
        return this;
    }


alert(Array.prototype.remove.prototype.constructor);

Non-enumerable methods do not expose their code

kennebec
  • 102,654
  • 32
  • 106
  • 127