简体   繁体   English

Javascript中的OOP原型和继承

[英]OOP Protoype and Inheritance in Javascript

I am a newbie in Javascript and I just finished the long Javascript course in codeAcademy. 我是Javascript的新手,我刚刚在codeAcademy完成了很长的Javascript课程。 I have some question regards prototype . 我对prototype有一些疑问。 I understand that prototype is mostly used for inheritance and also to dynamically define methods to an object. 我知道prototype主要用于继承,也可以动态定义对象的方法。

But I still have some questions. 但我还是有一些问题。 Look at my code. 看看我的代码。 I defined a toString in the object Animal and also another toString , using prototype. 我在对象Animal定义了一个toString ,并使用prototype定义了另一个toString When I run it, why it displays : [Object] Dumbo 4 and not [Proto] Dumbo 4 ? 当我运行它时,它显示为什么: [Object] Dumbo 4而不是[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. JavaScript是一种原型的面向对象的编程语言,它只是意味着对象继承自其他对象。 In JavaScript when a property is not found on an object then the interpreter tries to find it in the object's prototype chain. 在JavaScript中,当在对象上找不到属性时,解释器会尝试在对象的原型链中找到它。 If the object is not found in the object's prototype chain either then the interpreter returns undefined : 如果在对象的原型链中找不到对象,则解释器返回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 . 如您所见, var animal = new Animal("Dumbo", 4)继承自Animal.prototype Hence when you call animal.toString() it will execute the function defined inside the Animal constructor. 因此,当您调用animal.toString() ,它将执行Animal构造函数中定义的函数。 If you delete animal.toString and then call animal.toString then it will call Animal.prototype.toString instead. 如果你delete animal.toString ,然后调用animal.toString那么它将调用Animal.prototype.toString

Read the following blog post to learn more about prototypal inheritance in JavaScript: Why Prototypal Inheritance Matters 阅读以下博客文章,了解有关JavaScript中原型继承的更多信息: 为什么原型继承很重要

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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