zoukankan      html  css  js  c++  java
  • ES5,ES6的类,原型,静态方法

     
    静态方法:属于类的方法,即类可以直接调用的方法。为类所有实例化对象所共用(但不能用实例对象之间调用),所以静态成员只在内存中占一块区域;

    实例方法:属于实例化类后对象的方法,即实例对象调用的方法。每创建一个类的实例,都会在内存中为非静态成员分配一块存储;

      静态方法在一启动时就实例化了,因而静态内存是连续的,且静态内存是有限制的;而非静态方法是在程序运行中生成内存的,申请的是离散的空间。

    ES5:

      类:
    
            function Person(name,age){
                this.name = name;
                this.age = age;
                this.run = function(){
                    console.log(`${this.name}----${this.age}`)
                }
            }
     
        原型: 
            Person.prototype.sex='男';
            Person.prototype.work = function(){
                console.log(`${this.name}----${this.age}----${this.sex}`)
            }
            
        静态方法:
            Person.setName = function(){  
                console.log("静态方法")
            }
     
            var p = new Person('张三',11);
           类Person直接调用: Person.setName()      //输出:静态方法
           实例对象不能调用:  p.setName() 
           实例对象调用类的属性方法:p.run();    //输出:张三----11
           实例对象调用原型方法:p.work();    //输出:张三----11----男

    ES6:

       类:
            class Person{    // 作为对象的模板,可以看作构造函数的另一种写法
              constructor(name,age){  /** 类的构造函数,new 命令创建对象实例时,自动调用该方法,用来接收参数 **/
                this.name = name;  
                this.age = age;
              } 
              getName(){
                console.log(this.name);
              }
              setName(name){
                  this.name = name
              }
              getInfo(){
                  console.log(`姓名:${this.name}---年龄:${this.age}`)
              }
          静态方法:
              static work(){
                  console.log("这是es6里的静态方法")
              }
            }
    
            var p = new Person('李四','20')  
            p.getName()  //输出:李四
            p.setName('张三') 
            p.getName()  //输出:张三
            Person.work();  //这是es6里的静态方法

     

     
     
     
     
     
     
     
  • 相关阅读:
    左孩子右兄弟的字典树
    UVA 1401 Remember the Word
    HDOJ 4770 Lights Against Dudely
    UvaLA 3938 "Ray, Pass me the dishes!"
    UVA
    Codeforces 215A A.Sereja and Coat Rack
    Codeforces 215B B.Sereja and Suffixes
    HDU 4788 Hard Disk Drive
    HDU 2095 find your present (2)
    图的连通性问题—学习笔记
  • 原文地址:https://www.cnblogs.com/init00/p/12581149.html
Copyright © 2011-2022 走看看