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])。
  • 相关阅读:
    更好的抽屉效果(ios)
    系统拍照动画
    UITabBarController详解
    touch事件分发
    iOS UWebView详解
    iOS 监听声音按键
    webservice偶尔报黄页,解决方案
    FastReport脚本把数据绑定到文本控件上
    [转]js版的md5()
    JQuery中$.ajax()方法参数详解
  • 原文地址:https://www.cnblogs.com/dreamsboy/p/6648858.html
Copyright © 2011-2022 走看看