JavaScript对象的创造方法和包装类

版权声明:iQXQZX https://blog.csdn.net/Cherishlife_/article/details/87904799

一。JavaScript中,创建对象的方式包括两种:对象字面量和使用new表达式。

1.对象字面量:

var obj = {
    name : "obj",
    age : 19,
    say : function () {
        console.log("eating");
    }

};  //  plainObject  对象字面量

2.使用new  表达式:

    <1>. 使用系统自带构造函数

var obj = new Object();

    <2>.  自定义构造函数

function Person (name, height) {
    
    that.name = name;
    that.height = height;

}

var person1 = new Person("小娜", 100);

自定义构造函数的原理如下

function Person() {
    // 先隐式生成 this 对象(构造函数内部原理)
    // var this = {
    //     name : "",
    //     age : ,
    //     height : 
    // }

    this.name = "小娜";
    this.age = 18;
    this.height = 100;
    this.run = function () { };

    // 最后隐式返回
    // return this;
}


//   上面等价于下面的
function Person() {
    
    var that = {
        name : "",
        age : ,
        height : ,
    }

    that.name = "小娜";
    that.age = 18;
    that.height = 100;
    that.run = function () { };

    最后返回
    return that;
}

二。包装类

new Boolean()      new String()     new Number()  这都是包装类

var num = 4;  // 原始值
num.len = 3;
/* 当执行第二行是 会隐式生成  new Number(4).len = 3;
 生成之后  js解释器觉得他不对  然后他帮你用delete删除 */

console.log(num.len);

// 当你再次访问的时候  他会再次帮你生成  
// new Number(4).len = undefined;

// 然而字符串不同

var str = "aaaa";
str.length = 2;
//  依据上面的步骤  先new String("aaaa").length = 2  再 js解释器帮你 delete

console.log(str.length); // 结果为 4
// 会有 new String("aaaa").length = 4;
// 因为String 包装类里面有 length属性

猜你喜欢

转载自blog.csdn.net/Cherishlife_/article/details/87904799