MDN || Using prototypes in JavaScript

Hi There…
I understood the following article quite well, I think, But in the last section of it in the examples, I did not understand why :

console.log("doSomething.foo:            " + doSomething.foo);

returns: “undefined”.

I know it doesn’t already exist in ( doSomething ), but it’s in : ( prototype ) of (doSomething), isn’t it supposed to :

If doSomething does not have the property, then the browser looks for the property in the __proto__ of doSomething

Can I get clarification?

the following article :point_down::

in the examples :point_down::

Welcome back, @albaraa_1949

This is an excellent question! I think the source of the confusion is (at least for me it was): The prototype property of an object (like doSomething.prototype) doesn’t point to the prototype of the object). On Object prototypes - Learn web development | MDN MDN has following message:

Warning: The prototype property is one of the most confusingly-named parts of JavaScript — you might think that it points to the prototype object of the current object, but it doesn’t (that’s an internal object that can be accessed by __proto__ , remember?). prototype instead is a property containing an object on which you define members that you want to be inherited.

Let’s look at your linked example to understand this concept. A bit above the example we can see the result of console.log( doSomeInstancing );:

{
    prop: "some value",
    __proto__: {
        foo: "bar",
        constructor: ƒ doSomething(),
        __proto__: {
            constructor: ƒ Object(),
            hasOwnProperty: ƒ hasOwnProperty(),
            isPrototypeOf: ƒ isPrototypeOf(),
            propertyIsEnumerable: ƒ propertyIsEnumerable(),
            toLocaleString: ƒ toLocaleString(),
            toString: ƒ toString(),
            valueOf: ƒ valueOf()
        }
    }
}

In the prototype of doSomeInstancing (the first __proto__) we see the foo property and the constructor function doSomething() side by side. When calling doSomething.foo then (as you correctly observed) foo isn’t found. Now it will look inside the prototype of doSomething for foo. As we learned above that isn’t doSomething.prototype but the __proto__ of doSomething() (not shown in the console output above). doSomething() is a function so it’s prototype is Function (and the prototype of Function is Object). As all of them don’t contain foo we get undefined as a result.

I hope that clears things up a bit. These details of the prototypical inheritance sure are complicated and confusing :sweat_smile:

I wish you all the best,
Michael

2 Likes

Thank you very much, I am really grateful to you.

1 Like