Prototypes in JavaScript – FunFunFunction #16




Let’s say that you have a food type, and you want to make lots of different instances of that food, such as waffles, and I don’t know why you’d want any other food than waffles, but maybe you like carrots or something. In that context, *food* is the prototype of *waffles* and *carrots*.

Some of you will be thinking – that reminds me of classes! You’d be right, but they are not the same thing, so try to put classes aside and think of prototypes as something completely new – if you try to shove prototypes into the same place in your brain where you keep classes you’ll be very unhappy.

Music by http://incompetech.com/

Original source


20 responses to “Prototypes in JavaScript – FunFunFunction #16”

  1. At 7:34 I have a confusion as when we did waffle.init('waffle')
    and then did waffle.eat(), it gave an output as = you ate the waffle
    then we wrote food.type = 'dsgvgskjhgkjiuguiyg' and then calling waffle.eat() gave the output as= you ate the waffle
    [please explain this part, I thought it should have given output as = you ate dsgvgskjhgkjiuguiyg]
    THANKS

  2. 8:40 Reminiscent of the scope chain: initially, it looks inside its lexical scope–if not found, it searches inside its external context–and so on. Once it reaches the global context, and it's still not there, it will return undefined.

    Question, does the prototype chain work the same way, or does it fallback only on its direct parent?

  3. Thank you for so many great videos and content.

    While not directly related, I think its important for future users that if you are using arrow functions like this
    eat: () => {
    console.log('You ate the ', this._type);
    }

    , the code at @7:43 will not work as the this context at the time of execution will not be waffle but global.

    The right way would be use shorthand syntax (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions)

    eat() {
    console.log('You ate the ', this._type);
    }

  4. At 5:58 or so, when you're talking about `food` as a "fallback" to `carrot` and `waffle`, might a better explanation be something like "Creating `waffle` and `carrot` creates empty objects that delegate to `food` for any method or property references"? That further reinforces the difference between JS objects and OO "classes"; delegation Is Not The Same Thing As inheritance.

  5. I have a question:
    At line 5 – food object has eat function printing 'you are the ' + this. type
    At line 12 – wrote again food.eat = function() { blah blah }.
    What's the difference? when we when we do waffle.eat() why did it pick the method from line 12 ? answer please… Thank you

Leave a Reply