zoukankan      html  css  js  c++  java
  • js-原型以及继承小案例

     1 function human(name,tall){
     2     this.name=name;
     3     this.tall=tall;
     4     this.toSleep=function(){
     5         alert('no sleep');
     6     }
     7 }
     8 
     9 human.prototype.toSleep=function(){
    10     alert('sleep');
    11 }
    12 
    13 var meimei=new human("meimei",160);
    14 var xiaoqiang=new human("xiaoqiang",170);
    15 
    16 //会先去找meimei这个对象中是否含有toSleep方法
    17 //如果没有就会去原型中即human构造器找,这样两个就会相等meiemi.toSleep()==xiaoqiang.toSleep()为true
    18 meiemi.toSleep();
    情况1:
    function animal(legs){
        this.leg=legs;
    }
    
    function human(name,tall){
        this.name=name;
        this.tall=tall;
    }
    human.prototype=new animal(2);
    
    var meimei=new human("meimei",160);
    var xiaoqiang=new human("xiaoqiang",170);
    
    meimei.leg
    
    
    
    
    情况2:
    function animal(legs){
        this.leg=legs;
    }
    
    function human(name,tall){
        this.name=name;
        this.tall=tall;
    }
    
    human.prototype.head=1;
    human.prototype={leg:2}; //整个对象被替换
    human.prototype.leg=2; 
    
    var meimei=new human("meimei",160);
    var xiaoqiang=new human("xiaoqiang",170);
    
    meimei.leg
    
    
    
    情况3:call()以及apply()
    function sleep(){
        alert(this.name+"to Sleep");
    }
    sleep();  ----window对象调用
    
    **********************************
    var meiemi={
        name:'meiemi',
        sleep:sleep
    }
    meimei.sleep(); ----meimei to Sleep
    
    
    **********************************
    var meiemi={
        name:'meiemi'
    }
    sleep.call(meimei); ----meimei to Sleep
    
    ***********************************
    function sleep(time){
        alert(time+":"+this.name+"to Sleep");
    }
    var meiemi={
        name:'meiemi'
    }
    sleep.call(meimei,"21:00");  ----传参方式不一样
    sleep.apply(meimei,["21:00"]) 
    
    
    
    
    情况4:
    类式继承:
    function Super(){
        this.colors=["red","blue"];  //this为Super.call(this)传入的对象,该对象返回的结果就有一个colors
    }
    function Sub(){
        //Super方法的执行环境改成了this
        //this是new Super是创建的对象,最后被返回的对象
        Super.call(this);  
    }
    
    ***********************************
    原型式继承:
    function obj(o){
        function F(){}
        F.prototype=o;  //new了一个对象,但原型指向o
        return new F();
    }
    var box={
        name:'zhang',
        arr:['borther','sister']
    };
    var b1=obj(box);  //没有new了,在方法中内部创建了
    alert(b1.name);
    **********************************
  • 相关阅读:
    [转]用异或交换两个整数的陷阱
    线索化二叉树
    [转]Socket编程中,阻塞与非阻塞的区别
    两个链表的归并
    [转] std::string and stl 算法
    类图
    leetcode 答案
    about raw socket
    54. Spiral Matrix【数组】
    矩阵乘法问题的实现
  • 原文地址:https://www.cnblogs.com/zhanghuiyun/p/5166231.html
Copyright © 2011-2022 走看看