zoukankan      html  css  js  c++  java
  • js实现继承的5种方式

    1.对象冒充:

    function Parent(username){
        this.username = username;
        this.hello = function(){
             alert(this.username);
        }
    }
    function Child(username,password){
        this.method = Parent;
        this.method(username);//最关键的一行
        delete this.method;
        this.password = password;
        this.world = function(){
             alert(this.password);
        }
    }
    var parent = new Parent("zhangsan");
    var child = new Child("lisi","123456");
    parent.hello();
    child.hello();
    child.world();

    2.call()方法:

    function Parent(username){
        this.username = username;
        this.hello = function(){
             alert(this.username);
        }
    }
     function Child(username,password){
         Parent.call(this,username);
         this.password = password;
         this.world = function(){
              alert(this.password);
         }
     }
    var parent = new Parent("zhangsan");
    var child = new Child("lisi","123456");
    parent.hello();
    child.hello();
    child.world();

    3.apply()方法:

    function Parent(username){
        this.username = username;
        this.hello = function(){
             alert(this.username);
        }
    }
    function Child(username,password){
        Parent.apply(this,new Array(username));
        this.password = password;
        this.world = function(){
             alert(this.password);
        }
    }
    var parent = new Parent("zhangsan");
    var child = new Child("lisi","123456");
    parent.hello();
    child.hello();
    child.world();

    4.原型链:

    function Person(){}
    Person.prototype.hello = "hello";
    Person.prototype.sayHello = function(){
         alert(this.hello);
    }
    function Child(){}
    Child.prototype = new Person();//这行的作用是:将Parent中将所有通过prototype追加的属性和方法都追加到Child,从而实现了继承
    Child.prototype.world = "world";
    Child.prototype.sayWorld = function(){
         alert(this.world);
    }
    var c = new Child();
    c.sayHello();
    c.sayWorld();

    5.call()方法与原型链混合:

    function Parent(hello){
        this.hello = hello;
    }
    Parent.prototype.sayHello = function(){
         alert(this.hello);
    }
    function Child(hello,world){
        Parent.call(this,hello);//将父类的属性继承过来
        this.world = world;//新增一些属性
    }
    Child.prototype = new Parent();//将父类的方法继承过来
    Child.prototype.sayWorld = function(){//新增一些方法
         alert(this.world);
    }
    var c = new Child("zhangsan","lisi");
    c.sayHello();
    c.sayWorld();
  • 相关阅读:
    博客园电子期刊2012年6月刊发布啦
    如何在博客园发博客时插入优酷视频
    上周热点回顾(7.167.22)
    “Coding changes the world” 博客园2012主题T恤专题上线
    [转]MySql查询缓存机制
    淘宝店铺开发 ShopSDK 1.x 及 TAE_SDK 2.0
    [转]NHibernate之旅系列文章导航
    MySQL 5.1参考手册 :: 7. 优化
    [转]Nant daily build实践
    [转]淘宝sdk——入门实战之footer.php制作
  • 原文地址:https://www.cnblogs.com/lxcmyf/p/6429637.html
Copyright © 2011-2022 走看看