zoukankan      html  css  js  c++  java
  • js 继承

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

    function Person(username){
        this.username=username;
        this.sayHello=function(){
            alert(this.username);
        }
    }
    
    function Child(username,password){
        this.superUserName=Person;
        this.superUserName(username);
        delete this.superUserName;
        
        this.sayWord=function(){
            alert(password);
        }
    }
    
    var a=new Person('a');
    a.sayHello();
    
    var b=new Child('b','2b');
    b.sayHello();
    b.sayWord();

    2. 使用Function的call方法

    function Person(username){
        this.username=username;
        this.sayHello=function(){
            alert(this.username);
        }
    }
    
    function Child(username,password){
        Person.call(this,username);
        
        this.sayWord=function(){
            alert(password);
        }
    }
    
    var a=new Person('a');
    a.sayHello();
    
    var b=new Child('b','2b');
    b.sayHello();
    b.sayWord();

    3.使用Function的apply方法

    function Person(username){
        this.username=username;
        this.sayHello=function(){
            alert(this.username);
        }
    }
    
    function Child(username,password){
        Person.apply(this,[username]);
        
        this.sayWord=function(){
            alert(password);
        }
    }
    
    var a=new Person('a');
    a.sayHello();
    
    var b=new Child('b','2b');
    b.sayHello();
    b.sayWord();

    4.原型方式实现继承(无法实现参数传递)

    function Person(){
    
    }
    
    Person.prototype.username='hello';
    Person.prototype.sayHello=function(){
        alert(this.username);
    }
    
    function Child(){
        
    }
    Child.prototype=new Person();
    Child.prototype.password='word';
    Child.prototype.sayWord=function(){
        alert(this.password);
    }
    
    var a=new Person();
    a.sayHello();
    
    var b=new Child();
    b.sayHello();
    b.sayWord();

    5.原型混合方式实现继承

    function Person(username){
        this.username=username;
    }
    Person.prototype.sayHello=function(){
        alert(this.username);
    }
    
    function Child(username,password){
        this.password=password;
        Person.call(this,username);
    }
    Child.prototype=new Person();
    Child.prototype.sayWord=function(){ //放在new Person后面,不然会被覆盖
        alert(this.password);
    }
    var a=new Person('a');
    a.sayHello();
    
    var b=new Child('b','2b');
    b.sayHello();
    b.sayWord();
  • 相关阅读:
    如何回答十个最棘手的面试问题(下)
    数据库设计三大范式应用实例剖析
    也谈内置无线网卡
    用10个漂亮问题完美结束面试
    Visual C++6.0编译器报错fatal error C1083
    MSDN library下载地址
    如何回答十个最棘手的面试问题(上)
    个人计划永不乱:五款定时提醒软件横评
    怎样使用C#调用exe的应用程序
    组策略妙用通过组策略禁止域用户更改IP地址
  • 原文地址:https://www.cnblogs.com/BigIdiot/p/2938241.html
Copyright © 2011-2022 走看看