温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JS怎么创建对象

发布时间:2022-02-08 09:33:46 来源:亿速云 阅读:187 作者:iii 栏目:开发技术

本篇内容主要讲解“JS怎么创建对象”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“JS怎么创建对象”吧!

一、new Object();

 var x="age"

        var obj=new Object();
        obj.name="wang";
        obj.x=20; //.字符串
        obj[x]=25; //[变量]
        console.log(obj);//{name: "wang", x: 20, age: 25}

二、字面量

 var a="hobby"
        var obj={"name":"wang","age":"18"};

            obj.sex="男";
            obj[a]="唱歌";
            obj.say=function(){
            }
            console.log(obj);//{name: "wang", age: "18", sex: "男", hobby: "唱歌", say: ƒ}
            var obj2={"aa bb":"hellow",".x":"world"};
            console.log(obj2["aa bb"]);//hellow
            console.log( obj2[".x"] );//world

三、工厂模式;

 //1.创建函数
        function a(name, age) {
            var obj = {
                "name": "wang",
                "age": 19,
                "say": function () {
                }
            }
            return obj
        }
        //2.依次调用
        var obj1 = a("wang", 20);
        console.log(obj1);//{name: "wang", age: 19, say: ƒ}
        console.log(obj1 instanceof Object);//true

            //优点:返回新对象,互不影响
            //缺点:代码重复(方法相同)。
            //  没有从属关系,

四、构造函数

 //四、构造函数;
        //优点:有从属
        //缺点:代码重复(相同方法);
         //   1.创建函数
         //2.传入参数
        function A(name,age){
            //3.this。属性名=值
            this.name=name;
            this.age=age;
            this.say=function(){
            }
        }
        //调用 : var obj=new 构造函数(参数)
        
        var obj= new A("wang",19);
        console.log(obj);
        console.log( obj instanceof Object );//true
        console.log( obj instanceof A );//true

五、原型模式

 //原型优点:共同/相同的属性、方法不重复 有从属关系
        //缺点:原型上的属性不可单独改变
        function Fn(){
            
        }
        Fn.prototype.name="王";
        Fn.prototype.age=19;

        var obj=new Fn();
        console.log(obj);
        /*
        修改obj.__proto__.name
        obj.__proto__.name 发生变化
        obj2.__proto__.name 也发生变化
        obj和obj1 共用__proto__对象
        公共/相同的属性、方法放在构造函数.prototype上 实现代码不重复
        */
            obj.__proto__.name="李"
            console.log( obj.__proto__.name  );

            var obj2=new Fn();
            console.log(obj2);
            console.log(obj.__proto__.name);

到此,相信大家对“JS怎么创建对象”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI