Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/472.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_Prototypal Inheritance - Fatal编程技术网

Javascript构造函数继承

Javascript构造函数继承,javascript,prototypal-inheritance,Javascript,Prototypal Inheritance,早上好,在我的时区 我正在学习JavaScript继承,并开始阅读MDN页面。 我知道我们必须使用构造函数中的prototype属性来构建继承链,例如: function Employee(){ this.name = "Dave"; this.dept = ""; } function Manager(){ this.projects = []; } Manager.prototype = new Employee; 如果我们这样做: var jane = new Manager()

早上好,在我的时区

我正在学习JavaScript继承,并开始阅读MDN页面。 我知道我们必须使用构造函数中的prototype属性来构建继承链,例如:

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

function Manager(){
 this.projects = [];
}
Manager.prototype = new Employee;
如果我们这样做:

var jane = new Manager();
jane.name->它将检索“Dave”,因为它将在Employee对象上找到

我不明白的是,如果你这样做:

 function Employee(name,dept){
 this.name = name || "Dave";
 this.dept = dept || "General";
}

function Manager(){
 this.base = Employee;
 this.base("Jack","CustpmDept");
 this.projects = [];
}
现在,如果我也这样做:

var jane = new Manager();
jane.name->它将检索“Jack”,因为它将在Employee对象上找到

在最后一个示例中,我没有使用line Manager.prototype=new Employee; 而且它仍然有效,经理对象的原型对象是Employee对象。 这怎么可能? 你能澄清一下吗

提前谢谢


致以最诚挚的问候第二种方式就像偷窃<代码>此.base(“Jack”、“custpdept”)将调用
Employee
构造函数,因为
这个
关键字将指向我们新建实例时要创建的对象,因此jane可以获得这些属性

function Manager(){
    this.base = Employee;
    this.base("Jack","CustpmDept");
    this.projects = [];
}

当您使用
this.base(“Jack”、“custpdept”)
时,in调用
Employee
,在
Employee
内使用
this
指向后者中的新经理实例,
new manager()
返回“Jack”,因为您调用
this.Employee('Jack',custpdept'))
jane.name
设置为“Jack”,因为“this”是“Manager”,在本例中是“jane”


这有点令人困惑。

好的,所以js处理上下文的方式很有趣


在管理器的构造函数中调用
this.base()
时,您正在从该管理器的上下文调用函数
base
。因此,当我们到达
this.name=
位时,关键字
this
引用的是该管理器,而不是该行写入的函数。

请查看以下代码:

function Employee(name,dept){
    this.name = name || "Dave";
    this.dept = dept || "General";
    console.log(this instanceof Manager);
}

function Manager(){
     this.base = Employee;
     this.base("Jack","CustpmDept");
     this.projects = [];
}

var jane = new Manager();
console.log(jane.name);
在这个例子中

console.log(this instanceof Manager);
返回true,因为当您调用

this.base = Employee;
你基本上是把经理的这封信发给员工。this.name和this.dept实际上是附加到经理的。

重复问题: