JS对象和包装类

对象是一种基础的变量类型,ES5对象。Javascript最大的特点是可以增加或者删除自己的属性和方法。

删除属性,再输出不存在的属性会显示undefined

var person = {
        DOB: '',
        name: '',
        gender:'',
        phone:'',
        smoke: function(){
            console.log("cool!!");
        },
        swimm: 1
    }

    console.log(person.swimm);
    console.log(person.smoke());
    // 删除属性,再输出不存在的属性会显示undefined
    delete person.swimm;
    console.log(person.swimm);

 

对象的创建方法

    */
    // 1. 直接构造
    var obj1 = {}
    // 1.1 使用系统构造函数,等效于直接构造
    var obj2 = new Object();
    obj2.name = '系统构造';
   // 2.  工厂模式构造
    function Ob(){
    return {
      name: "hehe"
    };
   }
  var b = new Ob();

    // 3. 自定义构造函数:函数名称的一切首字母大写
    function Car(id){
        this.id = id;
        this.brand = "trash";
        this.changeBrand = function(br){
            this.brand = br;
        }
        // return {}; 这是捣乱
        // return this; 默认
        return 123; // new 了之后,返回的依然是this而不是123
    }
    var car = new Car(10);
    car.speed = 1000;
    console.log(car.speed);
    car.changeBrand("Bench");
    console.log(car.brand);
    var car1 = new Car(11);
    console.log(car1.brand);
    console.log(car1.id);

  // 4.ES6 创建类再实例化对象
  class Person{
        dob = "";
        name = "";
        phone = "";
        health = 100;
        constructor(dob){
            this.dob = dob;
        }

        smoking(){
            this.health--;
            return "Fuck!!";
        }

        getDOB(){
            return this.dob;
        }

        getHealth(){
            return this.health;
        }
    }

    var p = new Person("1994");
    p.smoking();
    console.log(p.getDOB());
    console.log(p.getHealth());

 

 

原始值如string,number是不能有属性和方法的

为了让原始值能够调用方法方便操作,JavaScript提供包装类来解决这些

    var x = 123;
    var s = "aaa";

    var x1 = new Number(123);
    console.log(x1.toFixed(2)); // 方法,返回前两位
    console.log(x+x1);
    var s1 = new String('abc');
    console.log(s1.repeat(2)); // 方法,复制一遍
    console.log(s+s1);

    

 

转换-元类型-》生成包装类 -》删除包装类 -》返回数据

    var l = s.length; // 系统后台:new String(s).length
    s.length = 1;
    // 系统后台:new String(s).length = 1,然后销毁String(s),不影响s
    console.log(s.length);

 

posted @ 2020-11-29 15:01  SvenWayne  阅读(80)  评论(0)    收藏  举报