简体   繁体   中英

OOP Protoype and Inheritance in Javascript

I am a newbie in Javascript and I just finished the long Javascript course in codeAcademy. I have some question regards prototype . I understand that prototype is mostly used for inheritance and also to dynamically define methods to an object.

But I still have some questions. Look at my code. I defined a toString in the object Animal and also another toString , using prototype. When I run it, why it displays : [Object] Dumbo 4 and not [Proto] Dumbo 4 ?

 function Animal(name, numLegs){
      this.name = name;
      this.numLegs = numLegs;

       this.toString = function(){
        return "[Object]" + this.name  + " " + this.numLegs + "\n";
        };
    }

    Animal.prototype.toString = function(){
     return "[Proto]" + this.name  + " " + this.numLegs + "\n";
    };

    var animal = new Animal("Dumbo", 4);
    console.log(animal.toString());

JavaScript is a prototypal object-oriented programming language which simply means that objects inherit from other objects. In JavaScript when a property is not found on an object then the interpreter tries to find it in the object's prototype chain. If the object is not found in the object's prototype chain either then the interpreter returns undefined :

        null
          ^
          | [prototype]
          |
+------------------+
| Object.prototype |
+------------------+
          ^
          | [prototype]
          |
+------------------+
| Animal.prototype |
+------------------+
          ^
          | [prototype]
          |
   +------------+
   | new Animal |
   +------------+

As you can see var animal = new Animal("Dumbo", 4) inherits from Animal.prototype . Hence when you call animal.toString() it will execute the function defined inside the Animal constructor. If you delete animal.toString and then call animal.toString then it will call Animal.prototype.toString instead.

Read the following blog post to learn more about prototypal inheritance in JavaScript: Why Prototypal Inheritance Matters

对象本身定义的属性优先于在其原型链中定义的属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM