【发布时间】:2015-03-25 20:24:02
【问题描述】:
请找出我创建继承的两种方法。谁能解释一下每种类型的情况。
方法一:
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name;
}
function Employee(name, designation){
Person.call(this, name);
this.designation = designation;
}
Employee.prototype = new Person();
Employee.prototype.constructor = Employee;
Employee.prototype.getDesignation = function(){
return this.designation;
}
new Employee("Jagadish", "Cons");
方法二:
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name;
}
function Employee(name, designation){
Person.call(this, name);
this. designation = designation;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.getDesignation = function(){
return this.designation;
}
new Employee("Jagadish", "Cons");
我已经插入了每个对象的控制台图像。在第一种方法中,我可以在 Person 类 中看到未定义的 name 属性(请参阅第一个屏幕截图)。
但在第二种继承方法的情况下,我在 Person 类中没有 name 属性。
有人可以深入解释一下这种行为以及后台发生的事情。
【问题讨论】:
标签: javascript inheritance prototype prototypal-inheritance