this Vs. prototype [duplicate]

Defining a function with whatever = function() { … } tends to create what’s called a “closure”, where the function can access local variables of the function that defines it. When you say this.fn = function() { … }, each object gets an instance of the function (and a new closure). This is often used … Read more

Javascript: hiding prototype methods in for loop?

You can achieve desired outcome from the other end by making the prototype methods not enumerable: Object.defineProperty(Array.prototype, “containsKey”, { enumerable: false, value: function(obj) { for(var key in this) if (key == obj) return true; return false; } }); This usually works better if you have control over method definitions, and in particular if you have … Read more

Why is it impossible to change constructor function from prototype?

You cannot change a constructor by reassigning to prototype.constructor What is happening is that Rabbit.prototype.constructor is a pointer to the original constructor (function Rabbit(){…}), so that users of the ‘class’ can detect the constructor from an instance. Therefore, when you try to do: Rabbit.prototype.constructor = function Rabbit() { this.jumps = “no”; }; You’re only going … Read more

Why does String.prototype log it’s object like a standard object, while Array.prototype logs it’s object like a standard array?

Because in a method call the this argument is always (in sloppy mode) casted to an object. What you see is a String object, which was produced from the “test” primitive string value. The array on which you call your method is already an object, so nothing happens and you just get the array as … Read more

Function.prototype is a function

The reason is that the ES5 spec says so: The Function prototype object is itself a Function object (its [[Class]] is “Function”) that, when invoked, accepts any arguments and returns undefined. Note it’s common in ES5 to make the prototype of some class a member of that class: Object.prototype is an Object object. Function.prototype is … Read more