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
  • 相关阅读:
    Socket规划(1)
    hdu 2391 Filthy Rich
    UDP议定书图像高速传输无损失程序
    C# 通过豆瓣网络编程API获取图书信息
    OS调度算法常用摘要
    mysql回想一下基础知识
    2015第37周三
    2015第37周二
    2015第37周一
    2015第37周一struts2 jstl 标签
  • 原文地址:https://www.cnblogs.com/zhangwei412827/p/2879126.html
Copyright © 2011-2022 走看看