javascript call函数实现继承时遇到的问题

javascript中用call函数可以实现继承,但有一个问题需要注意。请看下面代码:

// 构造函数
   function Person(name, sex) {
       this.name = name;
       this.sex = sex; 
   }

   // 定义Person的原型,原型中的属性可以被自定义对象引用
   Person.prototype = {
       getName: function() {
           return this.name;
       },
       getSex: function() {
           return this.sex;
       }
   }


   function Employee(name, sex, employeeID) {
    this.name = name;
    this.sex = sex;
    this.employeeID = employeeID;
    //用call方法 实现继承
    Person.call(this,name,sex);
}

Employee.prototype.getEmployeeID = function() {
    return this.employeeID;
};
var zhang = new Employee("ZhangSan", "man", "1234");
alert(zhang.getName()); // 此处出错,找不到getName函数

但是如果把Person的getName函数从原型中移到Person函数本身,也就是把getName变成Person函数的属性。则用上面代码就不会出错了,Employee也能找到

Person的getName函数了。

// 构造函数
   function Person(name, sex) {
       this.name = name;
       this.sex = sex; 
       this.getName=function(){
       return this.name;
       }
   }

   // 定义Person的原型,原型中的属性可以被自定义对象引用
   Person.prototype = { 
       getSex: function() {
           return this.sex;
       }
   }


   function Employee(name, sex, employeeID) {
    this.name = name;
    this.sex = sex;
    this.employeeID = employeeID;
    //用call方法 实现继承
    Person.call(this,name,sex);
} 
 
Employee.prototype.getEmployeeID = function() {
    return this.employeeID;
};
var zhang = new Employee("ZhangSan", "man", "1234");
//console.log(zhang.getName()); // "ZhangSan
alert(zhang.getName()); // "ZhangSan
原文地址:https://www.cnblogs.com/zhangwei412827/p/2879126.html