JS --- 对象的创建

1、object 类型构造函数

        var obj1 = new Object();
        var arr = new Array();
        var str = new String();
        //添加属性
        obj1.name = "zhangsan";
        // 添加方法
        obj1.play = function(){
            console.log(this.name + '在play');
        }

2、字面量定义

        var obj2 = {}
        obj2.name = 'zhangsan'
        obj2.age = 22 ;
        obj2['name'] = 'lisi'
        obj2['age'] = 55;
        // 嵌套字面量
        var obj3 = {
            name:'wangwu',
            age:22,
            other:{
                hobby:['足球','篮球'],
                sex:'男'
            }
        }

3、工厂方法定义

       function createObj(name,age){
            var obj = new Object();
            obj.name = name;
            obj.age = age;
            obj.eat = function(){};
            return obj;
        }
        var o1 = new createObj('zhangsan',20);
        var o2 = new createObj('lisi',24);

4、构造函数

      function CreateObj(name,age){
            this.name = name;
            this.age = age;
            this.play = function(){
                console.log(this.name + 'is playing');
            }
        }
        var c1 = new CreateObj('lili',20)
        var c2 = new CreateObj('lucy',23)

5、Object.create()

       var objc = {
            name:'wangergou',
            age:24
        }
        var objc1 = Object.create(objc);
        console.log(objc1.__proto__);// objc1.__proto__ === objc

你可能感兴趣的:(JS --- 对象的创建)