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
  • 相关阅读:
    在线JS代码调试网址
    NVM在windows系统下载及安装
    浏览器【插件】【扩展】下载安装
    JavaScript 秘密花园
    HTTP 协议
    移动端:zepto框架
    移动端:移动端事件
    移动端:移动端页面布局
    移动端:Flex弹性盒布局
    移动端:自适应和响应式布局
  • 原文地址:https://www.cnblogs.com/zhangwei412827/p/2879126.html
Copyright © 2011-2022 走看看