简体   繁体   English

是否有必要在JavaScript中具有原型继承,以便我们可以动态传播添加的新属性?

[英]Is it necessary to have prototypal inheritance in JavaScript just so we can dynamically propagate new properties we add?

I have been brushing up on prototypal inheritance in JavaScript and I have a major question about its necessity. 我一直在研究JavaScript中的原型继承,并且对它的必要性有一个主要问题。 I am unable to grasp the reasons why it is very important. 我无法理解为什么它非常重要的原因。 I have been running the basic code snippet shown below : 我一直在运行下面显示的基本代码段:

 function Employee() { this.name = "geetha"; this.dept = "general"; } Employee.prototype.designation = "nothing"; function Manager() { Employee.call(this); this.title = "mr"; } Manager.prototype = Object.create(Employee.prototype); var mark = new Manager; console.log(mark.name); console.log(mark.dept); console.log(mark.title); console.log(mark.designation); 
 <script src="https://getfirebug.com/firebug-lite-debug.js"></script> 

In the above snippet, if I remove 在以上代码段中,如果我删除了

 Manager.prototype = Object.create(Employee.prototype); 

I can see it only impedes me from adding a new property on the go for the "Employee" constructor such that it trickles down to the objects it is a prototype of. 我可以看到,这仅阻止了我随时随地为“ Employee”构造函数添加新属性,从而使它滴落到原型的对象上。 Otherwise, if I am content with the properties already defined, I don't really need to make "Employee" the prototype of "Manager". 否则,如果我对已经定义的属性感到满意,那么我真的不需要使“雇员”成为“经理”的原型。 The constructor call of Employee from inside Manager would accomplish the getting of its properties. 从Manager内部调用Employee的构造函数将完成其属性的获取。 So am I missing something really important in this concept? 那么我是否错过了这个概念中真正重要的东西?

Thanks! 谢谢!

If you don't use the line 如果您不使用线路

Manager.prototype = Object.create(Employee.prototype);

then you are not actually using inheritance. 那么您实际上并没有使用继承。 You are simply using the Employee constructor to initialise the variables in the Manager instance just as they would be initalised in an Employee instance. 您只需使用Employee构造函数来初始化Manager实例中的变量,就像在Employee实例中将其初始化一样。

The thing to note is this line 需要注意的是这条线

Employee.prototype.designation = "nothing";

If you do not use inheritance then the property designation will not available to Manager instances because it will not be in the prototype chain. 如果您不使用继承,则属性designation将对Manager实例不可用,因为它不在原型链中。

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

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