In Javascript terminology, a "prototype" refers to the object from which a inherits properties. The standard way to access this is with Object.getPrototypeOf :
var protoOfA = Object.getPrototypeOf(a);
There is also an old way, non-standard, but supported by some browsers:
var protoOfA = a.__proto__;
But if you have an F function, F.prototype does NOT refer to the object from which F inherits anything. Rather, this refers to the object from which the instances created by F inherit are:
function F() {}; a = new F(); console.log(Object.getPrototypeOf(a) === F.prototype);
When you define a function, an object is created that serves as the prototype of the instances created by this function, and this new object is stored in the prototype function property.
-
Functions behave like objects in different ways (for example, they can have properties), but they are not quite like other objects:
console.log(typeof a); // "object" console.log(typeof F); // "function"
Their "prototypes" are poorly defined (the example runs in Chrome) (this is apparently the behavior typical of Chrome )
console.log(Object.getPrototypeOf(F)); // "function Empty() {}" console.log(Empty); // ReferenceError: Empty is not defined
-
The constructor property is strange. The translator does not care about this . MDN says vaguely :
Returns a reference to the Object function that created the instance prototype.
In addition, you can change the constructor value to an object, but this does not affect what the object is or how it behaves - it is simply descriptive.
-
So, to answer your questions:
Why x.constructor === x.constructor.prototype.constructor
There is no good reason. These are arbitrary behavior browsers converge.
which object is x.constructor.prototype, anyway
In this example, the t x prototype is similar to Object.getPrototypeOf(x) . But in general, you cannot rely on x.constructor or anything derived from it, because it is arbitrary.
How can the above algorithm be eliminated in order to correctly go through the prototype chain for object x?
for (var p = x ; p != null ; p = Object.getPrototypeOf(p)) {