Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/456.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript继承调用行为_Javascript_Inheritance_Prototype - Fatal编程技术网

Javascript继承调用行为

Javascript继承调用行为,javascript,inheritance,prototype,Javascript,Inheritance,Prototype,在经历和遇到这种简单的关系 function Employee() { this.name = ""; this.dept = "general"; } function Manager() { Employee.call(this); this.reports = []; } Manager.prototype = Object.create(Employee.prototype); 显然,这形成了一种从员工到经理的继承式关系 这里有两个问题,不确定是什么和为什么Emp

在经历和遇到这种简单的关系

function Employee() {
   this.name = "";
   this.dept = "general";
}

function Manager() {
  Employee.call(this);
  this.reports = [];
}
Manager.prototype = Object.create(Employee.prototype);
显然,这形成了一种从员工到经理的继承式关系

这里有两个问题,不确定是什么和为什么
Employee.call(this)有和吗
将对象分配给
Employee.prototype
而不是
Manager.prototype
。我的想法是,经理是从员工那里继承,而不是从员工那里继承。也许这就是原型链的概念,它真正意味着两个对象都可以从彼此获取属性

我想澄清一下

  • Employee.call(this)
    类似于调用
    Employee()
    ,但它不是用来创建新对象,而是修改当前的
    管理器。在本例中,它在
    管理器中设置
    名称
    部门
  • 本声明:

    Manager.prototype = Object.create(Employee.prototype);
    
    这意味着任何属性集,如
    Employee.prototype.x=val
    也将在
    Manager.prototype
    中可用;但是,如果在
    Manager.prototype
    中覆盖它们,它们将被覆盖。
    您还应该运行
    Manager.prototype.constructor=Manager
    ,以使该属性正确


  • 经理将继承Employee类的属性,并将拥有自己的属性/方法。但是Employee类不会继承Manager的属性。“而不是将对象分配给
    Employee.prototype
    ”-哪个对象?@Bergi
    Employee.prototype=object.create(Manager.prototype)
    @Aaron是的,这将员工的原型设置为从经理的原型继承的对象。@Aaron:哦,我错过了你在那里将
    Employee
    Manager
    交换的内容。正确的。但不,员工的原型不应该“有经理对象”。
    Employee
    类不关心哪些子类在扩展它,也不保存对它们的引用。如果管理者是从员工继承的,那么原型链链接从
    Manager.prototype
    Employee.prototype
    ,而不是反过来。可以将
    Employee.call(this)
    看作Java中的
    super()
    吗?我认为类似。(不过我不懂Java)。@Aaron:是的,它就是这么做的。它调用子实例上的父构造函数来创建和初始化父属性。@JF:
    对象。create
    不复制任何内容。JF的答案是否错误?他的解释对我来说非常清楚。不理解落选票。