• javascript继承


    拷贝继承

     1    function Foo(){   //父类
     2         this.name = 'hello';
     3     }
     4     Foo.prototype.showName = function(){
     5         console.log(this.name);
     6     };
     7     function Bar(){   //子类
     8         Foo.call(this);
     9         this.age = 20;
    10         this.name = 'hi'
    11     }
    12     extend(Bar,Foo);
    13     Bar.prototype.showAge = function(){
    14         console.log(this.age);
    15     };
    16     function extend(subs,sups){
    17         for(var attr in sups.prototype){
    18             subs.prototype[attr] = sups.prototype[attr];
    19         }
    20     }
    21     var obj1 = new Foo();
    22     var obj2 = new Bar();
    23     console.log(obj1);
    24     console.log(obj2);
    25     obj2.showName()

    类式继承

     1     function Foo(){
     2         this.name = 'hello';
     3     }
     4     Foo.prototype.showName = function(){
     5         console.log(this.name);
     6     };
     7     function Bar(){
     8         Foo.call(this);
     9         this.age = 20;
    10     }
    11     extend(Bar,Foo);
    12     Bar.prototype.showAge = function(){
    13         console.log(this.age);
    14     };
    15     function extend(subs,sups){
    16         var F = function(){};
    17         F.prototype = sups.prototype;
    18         subs.prototype = new F();
    19     // constructor 找对应的构造函数;
    20         subs.prototype.constructor = subs;
    21     }
    22     var obj1 = new Foo();
    23     var obj2 = new Bar();
    24     console.log(obj1);
    25     console.log(obj2);

    非构造函数拷贝继承

     1     var foo = {
     2         name : 'hello'
     3     };
     4     foo.showName = function(){
     5         console.log(this.name)
     6     }
     7     var bar = extend(foo);
     8     function extend(sups){
     9         var result = {};
    10         for(var attr in sups){
    11             result[attr] = sups[attr];
    12         }
    13         return result;
    14     }
    15     console.log(bar);
    16     bar.name = 'hi';
    17     console.log(bar);
    18     console.log(foo);
    19     bar.showName();

    原型链形式

     1    var foo = {
     2         name : 'hello',
     3         showName: function(){
     4             console.log(this.name)
     5         }
     6     };
     7     var bar = extend(foo);
     8     function extend(sups){
     9         function F() {}
    10         F.prototype = sups;
    11     return new F();
    12     }
    13     console.log(bar);
    14     bar.name = 'hi';
    15     console.log(bar);
    16     console.log(foo);
    17     bar.showName()
  • 相关阅读:
    wikiquote
    zz 勵志貼,成功是努力加对的方向
    # 电纸书
    # 崔寶秋
    好的程序員
    深度学习引擎
    再见乱码:5分钟读懂MySQL字符集设置
    Linux基础:用tcpdump抓包
    Linux基础:文件查找find
    Linux基础:xargs命令
  • 原文地址:https://www.cnblogs.com/lvshaonan/p/8520895.html
Copyright © 2020-2023  润新知