js-3原型链属性检测,对象的几个方法,对象的深拷贝,对象属性的特征的修改,访问器

1原型链属性检测对象的父类

  1. 将b 设置成a的原型
    a可以使用b的属性
    Object.setPrototypeOf(obj, prototype)
    参数
    obj
    要设置其原型的对象。.
    prototype
    该对象的新原型(一个对象 或 null)
    let a = {
        name:"刘兴加"
    };

    let b = {
        url:"houdunren.com"
    };

    Object.setPrototypeOf(a,b);
    console.log(a);
    console.log(a.hasOwnProperty("url"));
    console.log("url" in a);

2.a.hasOwnProperty(“url”)只能检测属性在不在对象中,(“url” in a)in能检测属性在不在a的原型链中或者a中

function oss(options) {
        if(!options.hasOwnProperty("host")){
            throw new Error("必须设置主机地址");
        
        }
    }

    oss({user:"admin",host :"192.168"});

2 解构默认值实现配置项合并

利用解构来更更方便的传递参数

function createElement(options = {}) {
        let {width = 200,height = 100, backgroundColor = "red"} =options;

                const div = document.createElement("div");
                div.style.width = width + "px";
                div.style.height = height + "px";
                div.style.backgroundColor = backgroundColor;
                document.body.appendChild(div);

    }

    createElement({backgroundColor:"green"});

3.assign(

1.assign()函数将两个对象合并成一个对象。重复属性用后一个代替前一个
2.JSON.stringify(options, null, 2)打印对象

 let hd = Object.assign({a:1}, {b:2});
    console.log(hd);

{…}

a: 1

b: 2

: Object { … }
计算属性assign.html:42:13

function upload(params) {
       let options = {size :200};
        options = Object.assign(options,params);
        console.log(options);
   }

   upload({size:99, type:"jpeg"});

3.Object.keys(hd)。获取对象的属性名字,组成数组
Object.values(hd)。获取对象的属性值,组成数组
console.log(Object.entries(hd));属性名和属性值一起获取组成一个数组,数组再组成二维数组

console.log(Object.keys(hd));
console.log(Object.values(hd));
console.log(Object.entries(hd));

4. for in可以遍历对象的属性值,但for of不可以操作对象

for(const key in hd){
        console.log(key);
    }

但for of不可以操作对象,但利用它可以操作数组的特性,我们可以用以上提及的三种方法,将所需内容取出,组成数组,再用for of:

for(const i of Object.keys(hd)){
        console.log(i);
    }

或者将对象放到数组里

let cart = [
        { name: "iphone", price: 12},
        { name: "imac", price: 18},
        { name:"ipad", price: 3}
    ];
    let ul = document.createElement("ul");
    for(const good of cart){
        let li = document.createElement("li");
        li.innerHTML = `商品名称:${good.name}   \t  商品价格:${good.price}`;
        document.body.appendChild(ul);
        ul.appendChild(li);
    }

在这里插入图片描述

5对象数据类型的浅拷贝

1.let a={
name = b.name
}
2.遍历以赋值
for (const key in hd){
obj[key] = hd[key];
}
3.以空对象与目标对象合并,复制过程可以改变

let hd = {
        name:"刘兴加",
        sex:"femal"
    };
    let obj = {};
    obj = Object.assign({},hd);
    console.table(obj);

4.以展开语法
obj = {…hd}

6对象数据类型的深拷贝

深拷贝的代码,

    let data = {
        name:"刘兴加",
        user:{name:"lxj"},
        arr:[]
    };


    function copy(object){
        let res = object instanceof Array?[]:{};//是数组还是对象

        for(const [k,v] of Object.entries(object)){ //Object.entries是数组和对象通用的取值方法,统一了下一步的操作
            res[k] =  typeof v=="object"?copy(v):v;//进行下一次拷贝或直接赋值呢
        }
        return res;
    }

    let xj = copy(data);

    xj.arr.push("abc"); //测试数组的使用情况,是否有效
    data.user.name = "a~";  //测试对象的使用情况。
    console.table(JSON.stringify(data,null,2));
    console.table(JSON.stringify(xj,null,2));
    let a=[];
    console.log(a instanceof Object);
</script>

7构造函数

function User(name){
        this.name = name;
        this.show= function () {
            console.log(this.name);
        };
    }
    let lxj = new User("刘兴加");
    lxj.show();

8 对象属性的特征的修改

1.Obiect.defineProperties(user, “name”, {
value:12
writable:true,
// enumerable:false,
configurable:false,
})
设置或增加对象属性或特征
2.Object.getOwnPropertyDescriptor(user, “name”)
得到属性的描述

"use strict";
    const user={
        name:"lxj",
        
    }
    console.log(JSON.stringify(Object.getOwnPropertyDescriptor(user, "name")));
    Object.defineProperty(user, "age", {
        value:12,
        writable:true,
        // enumerable:false,
        configurable:false,
    });

    console.log(user.age);
    user.age = 3;
    console.log(user.age);
    delete user.age;
    console.log(JSON.stringify(Object.getOwnPropertyDescriptor(user, "age")));
    // console.log(Object.keys(user));

3.不允许对象添加新属性的设置preventExtensions
Object.preventExtensions(user)

判断是否能添加?Object.isExtensible(user)

const user={
        name:"lxj"
    }
    // Object.preventExtensions(user);
    if(Object.isExtensible(user)) {
        user.age = 13;
    }
    console.log(JSON.stringify(user,null,2));

4.不允许修改对象Object.seal(user)
不能加属性,不能删除,不能赋值
!Object.isSealed(user),Object.seal(user)

<script>
    const user={
        name:"lxj",
        age:18
    }
    // Object.seal(user);
    if(!Object.isSealed(user)){
        user.site = "www.cctv.com";
        delete  user.name;
    }
    console.log(JSON.stringify(Object.getOwnPropertyDescriptors(user),null,2));
</script>

{
“name”: {
“value”: “lxj”,
“writable”: true,
“enumerable”: true,
“configurable”: false
},
“age”: {
“value”: 18,
“writable”: true,
“enumerable”: true,
“configurable”: false
}
}

5 冻结:最简单,不允许任何修改啦,但还可以读取,
Object.freeze(user)

<script>
    const user={
        name:"lxj",
        age:18
    }
    // Object.freeze(user);
    if(!Object.isFrozen(user)){
        user.site = "www.cctv.com";
        delete  user.name;
    }
    console.log(JSON.stringify(Object.getOwnPropertyDescriptors(user),null,2));
</script>

9使用访问器

1.保护数据,写入对象数据时的动作(检验),和读取对象属性时的动作

const user={
        data:{
            name:"lxj",
            age:18
        },
        set age(value){
            if(typeof value!= "number" || value < 10 || value>90){
                throw new Error("年龄格式错误")
            }
            this.data.age = value;
        },

        get age(){
            return this.data.age + "岁";
        }

    };

    user.age = 20;
    console.log(user.age);

20岁

2伪造属性,将要获取的属性与函数绑定在一起,total不是属性,但可以通过属性的获取方式获取。却不可以通过属性的方式修改(理所当然)

 const user2={
        cart : [
            {name: "iphone", price: 12, click: 34},
            {name: "imac", price: 18, click: 36},
            {name: "ipad", price: 3, click: 56},
            {name: "xiaomi", price: 2, click: 66},
            {name: "huawei", price: 10, click: 55},
            {name: "sanxing", price: 4, click: 23}
        ],
        get total(){
            return this.cart.reduce((t,l) => t+ l.price , 0 );
        }
    };
    console.log(user2.total);

3批量设置属性

利用访问器,将属性值得到后用split函数分割成一个数组,再利用split方法分割成数组赋值给各个属性。

const user={
        data:{
            name:"lxj",
            age:18
        },
        set site(d){
            [this.name, this.age] = d.split(",");
        },

        get site(){
            return `${this.name} 的年龄是 ${this.age}`;
        }
    };

    user.site ="刘兴加, 23";
    console.log(user.site);

5 token通过访问器的读写处理

并没在对象中存储,只为简化代码

    "use strict"
    //token令牌
    let Request = {
        set token(content){
            localStorage.setItem("token", content);
        },

        get token(){
            let token = localStorage.getItem("token");
            if(!token){
                alert("请登录")
            }
            return token;
        }
    }
    // Request.token = "8375821585829";
    console.log(Request.token);

6访问器优先性高于普通的读取属性

直接写this.name会出现死循环,Symbol作为属性名使得不能直接通过 user.data.name的方式修改,有了很好的保密性。

"use strict"
    const DATA = Symbol();
    const user = {
        [DATA]:{
            name
        },

        age: 10,

        set name(v){
            this[DATA].name = v;
        },

        get name(){
            return this[DATA].name;
        }
};

    user.name = ",,,";
    console.log(user);

7构造函数与类语法糖中使用访问器

类语法糖中使用访问器更简洁易懂

const DATA = Symbol();
    class User{

        constructor(name, age){
            this[DATA]={name,age}
        }


        set name(value){
            if(value.trim() == "" || value.length>20){
                throw new Error("用户名不合法");
            }
            this[DATA].name = value;
        }

        set age(value){
            this[DATA].age = value;
        }

        get name(){
            return this[DATA].name;
        }
        get age(){
            return this[DATA].age;
        }
    }

    let xj = new User("刘兴加", 19);
    xj.name = "";
    console.log(xj.name);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值