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

    阮一峰的日志

    醍醐灌顶啊有木有,大神就是大神,知识好系统!

     继承
     一、原型继承

     1 //原型链核心是__proto__
     2   function Dog(){
     3       this.bark = function(){
     4           alert("wangwang")
     5       }
     6   }
     7   function Hashiqi(){
     8   }
     9   Hashiqi.prototype = new Dog();
    10  Hashiqi.prototype.constructor=Hashiqi;//强制更正构造器的指向
    11 var dog1 = new Hashiqi(); 12 dog1.bark();//wangwang 13 Hashiqi.prototype.bark = function(){ alert("wuwu"); } 14 var dog2 = new Hashiqi(); 15 dog2.bark();//wuwu 16 var dog3 = new Dog(); 17 dog3.bark();//wangwang

     二、对象冒充(使父构造函数在子构造函数中运行一遍)
    临时变量

    function Parent(){
    }
    function Child(){
        this.temp = Parent;
        this.temp();
        delete this.temp;
    }

    call()和apply()

    function Parent(){
    }
    function Child(){
       Parent.call(this,var1,var2...)
       //Parent.apply(this,[var1,var2...])
    }

    三、复制继承(把父构造函数的每个属性都复制一遍)

    Object.prototype.extend = function(obj){
        for(var key in obj){
            if(this[key]==undefined){
                this[key]=obj[key];
            }
        }
    }
    var cat = {color:"yellow",climb:function(){alert("我会爬树");}}
    var tiger = {color:"yellow and black"}
    tiger.extend(cat);
    tiger.climb();//我会爬树
    alert(tiger.color);//yellow and black


     静态方法(在对象上直接添加的方法,只属于该对象)

    //这是一个构造函数,也是一个对象
    function Bird(){
        this.wings=2;
        this.fly= function(){
            alert("我会飞");
        }
    }
    //这是Bird对象的静态方法,只属于此对象
    Bird.eat = function(){
       alert("吃虫子")
    }
    
    var niao = new Bird();//Bird的实例,不能访问eat()
  • 相关阅读:
    2016百度之星资格赛 Problem B(大数+组合数)
    HDU 4380 Farmer Greedy(叉积和三角形知识的综合应用)
    C++ STL (备忘)
    【Linked List Cycle II】cpp
    【Linked List Cycle】cpp
    【Copy List with Random Pointer】cpp
    【Reverse Nodes in k-Group】cpp
    【Swap Nodes in Pairs】cpp
    【Remove Nth Node From End of List】cpp
    【Rotate List】cpp
  • 原文地址:https://www.cnblogs.com/dll-ft/p/5796943.html
Copyright © 2011-2022 走看看