zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    设置导航条上的主题一颜色
    luogu_2158【题解】欧拉函数
    luogu_1313【题解】二项式定理
    【数论学习笔记】高斯消元
    luogu_2524【题解】康托展开
    luogu_1495【题解】中国剩余定理
    【数论学习笔记】 约数
    luogu_4430 luogu_4981【题解】 Cayley定理
    【数论学习笔记】质数
    【数论学习笔记】同余
  • 原文地址:https://www.cnblogs.com/zhangwei412827/p/2879126.html
Copyright © 2011-2022 走看看