Javascript Prototypal Inheritance?

后端 未结 5 2005
日久生厌
日久生厌 2021-02-04 05:43

I\'been doing some inheritance in js in order to understand it better, and I found something that confuses me.

I know that when you call an \'constructor function\' with

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 06:01

    You cannot change an object's prototype once it's been instantiated with new.

    In your example above, lines like

    fido.prototype = new KillerDog();
    

    simply creates a new attribute named prototype on the object fido, and sets that attribute to a new KillerDog object. It's no different than

    fido.foo = new KillerDog();
    

    As your code stands...

    // Doesn't work because objects can't be changed via their constructors
    fido.deathBite();
    
    // Does work, because objects can be changed dynamically, 
    // and Javascript won't complain when you use prototype 
    //as an object attribute name
    fido.prototype.deathBite();
    

    The special prototype behavior applies only to constructors in javascript, where constructors are functions that will be called with new.

提交回复
热议问题