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
  • 相关阅读:
    第十六节:类与对象基本概念
    dedecms源码分析:(1)index.php
    第十二节:控制结构foreachbreakcontinueswitch
    PHP的输出缓冲区(转)
    C 结构体小结
    指针参数在内存中的传递
    C typedef用途小结
    C语言考试2 题目整理
    MinGW 环境下 给hello.exe 自定义一个图标
    JavaEE程序设计快速入门小结
  • 原文地址:https://www.cnblogs.com/zhangwei412827/p/2879126.html
Copyright © 2011-2022 走看看