JS 对象

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <script >
            var person={
                name:"str",
                age:18,
                fullName:function(){
                    return this.name;
                }
            };
            //对象 x 并非 person 的副本。它就是 person。
            var x=person;
            
            //属性操作
                console.log(person.name);
                console.log(person["name"]);
                console.log(person[1]);
                
                person.city="hk";
                console.log(person);
                delete person.city;
            //方法操作
                console.log(person.fullName());
                
                person.getAge=function(){
                    return this.age;
                }
                console.log(person);
            //对象转化为数组
            var arr=Object.values(person);
            console.log(arr);
            //对象转化为字符串
            var str=JSON.stringify(person);
            console.log(str);
            
            //访问器 
            var point={
                x:1,
                y:2,
                z:null,
                set setZ(z){
                    this.z=z;
                },
                get getXY(){
                    return this.x+" "+this.y;
                }
            };
            point.setZ=5;
            console.log(point.z);
            console.log(point.getXY);
            
            //构造器 
            function Animal(name,city,age){
                this.name=name;
                this.city=city;
                this.age=age;
            }
                //构造器new出的对象各不同 添加的新属性方法互不影响
            var dog=new Animal("dog","hk",6);
            console.log(dog);
                //通过prototype添加新属性方法
                //无法通过 构造器名.新属性添加
            Animal.prototype.master="ssss";
            Animal.prototype.getName=function(){
                return this.name;
            };
            
            //对象方法
                //更改属性值
                Object.defineProperty(dog,"name",{value:"cat"});
                //writable     属性值可更改
                //enumerable   属性可枚举
                //configurable 属性可重新配置
                Object.defineProperty(dog,"name",{enumerable:false});
                //添加访问器
                Object.defineProperty(dog, "getName", {
                  get: function () {return this.name;}
                });
                //以数组返回所有属性
                Object.getOwnPropertyNames(dog)
        </script>
    </body>
</html>

 

posted @ 2022-03-10 22:18  lwx_R  阅读(18)  评论(0编辑  收藏  举报