Why some functions in JS have a prototype.constructor prop and others don’t? What is the difference between these functions?

StackOverflow https://stackoverflow.com/questions/12497859

Domanda

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?

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top