zoukankan      html  css  js  c++  java
  • 常见的对象继承方式

    对象继承常见方式

    • 通过原型链实现继承
    • 通过对象冒充实现继承
    • 通过call方式实现继承
    • 通过apply方式实现继承

    1.通过原型链实现继承如下所示

    function Person(name,age){
        this.name = name;
        this.age = age;
    }
       Person.prototype.sayHello = function(){
        alert('使用原型得到'+this.name);
       }
       var per = new Person('李端','26');
       per.sayHello();
       //创建新对象并实现继承
       function Student(){};
       Student.prototype = new Person('端瑞','23')
       var stu = new Student();
       stu.sayHello();
    

    2.使用对象冒充实现继承

    function Person(name,age){
           this.name = name ;
           this.age = age;
           this.showName = function(){
               alert('我是'+name);
        }
    }
        function Child(){
        //这三句代码最关键
           this.temp = Person;
           this.temp('李端','26');
           delete this.temp;
        }
        var child = new Child();
        child.showName();//我是李端
    

    3.通过call的方式实现

    function Person(name,age){
        this.name = name ;
        this.age = age;
        this.showName = function(){
            console.log('我是'+name);
        }
     }
     function Child(){
        Person.call(this,'李端','26');
     };
     var child = new Child();
     child.showName();
    

    4.通过apply方式实现

    function Person(name,age){
        this.name = name ;
        this.age = age;
        this.showName = function(){
            console.log('我是'+name);
        }
     }
     function Child(){
        Person.apply(this,['李端','26']);
     };
     var child = new Child();
     child.showName();
    // 注意:js中call和apply都可以实现继承,唯一的一点参数不同,func.call(func1,var1,var2,var3)对应的apply写法为:func.apply(func1,[var1,var2,var3])。
  • 相关阅读:
    111
    RH124-3 目录结构_转
    oracle 查看表空间以及日志文件等系统文件
    bash_profile
    linux 7 关闭防火墙 开启sshd服务
    mount 挂载光盘
    oracle 夸服务器、数据库查询
    Oracle中merge into的使用
    restore和recover的区别
    TCP: time wait bucket table overflow解决方法
  • 原文地址:https://www.cnblogs.com/dreamsboy/p/6648858.html
Copyright © 2011-2022 走看看