ways to creat an object in javascript


  
  
//ways to creat an object in javascript
function log(s){ console.log(s); }

1.the easyest way: literals    
var person={
    name:'windylcx',//here the comma is requried
    sex:'male'//no comma 
}
also we can use the string as the variable name(properties) ,it's the same.
var person={
    'name':'windylcx',
    'sex':'male'
}
once we creat the obj,we can acess its properties like this:
log(person.name) or log(person['name']);
//in addtion,we can also define the method of an object
//just set the properties(variable) the value of a function
var person={
    'name':'windylcx',
    'sex':'male',
    'getName':function(){
        return this.name;
    }
}
log(person.getName());
//to creat an empty object
var empty_obj={};
// add some properties into the obj
empty_obj.name='windylcx';
empty_obj.getName=function(){return this.name};

//2. use the new Object;
obj=new Object();//or obj=new Object;
//add properties
obj.name='lcw';
obj.getName=function(){return this.name;};
//console.log(obj.getName());


//3. use the Function Object;
//first define a function
function classA(name){
    this.name=name;// and then use the "this" key word to keep the object's properties;
    this.getName=function(){
        return this.name;
    }
    this.setName=function(name){
        this.name=name;
    }
    
    
}
//last use the new key word to creat a new Object;
var obj_a1=new classA(500);
/*
when the function is invocated by a "new" key word,
 it means to creat an object ,actually it will first do the following things:
 */
obj_a1.prototype.constructor=classA; 
/*
"When a function object is created, it is given a prototype member 
which is an object containing a constructor member
which is a reference to the function object"
actually this function(constructor) return "this";
 so when you use return statment in the constructor,it will not creat an 
 obj after you use "new" to creat an obj,it just as a ordinary function invocation;
 eg.*/
    function classC(){
        this.name=name;
        this.getName=function(){
            return this.name;
        }
        this.setName=function(name){
            this.name=name;
        }
        return {a:'a'};
    }
//and a better way is to use the prototype ,so that we can reduce the memory's useage.
//because we can just keep only one code as the common code.
 function classC(){
        this.name=name;
    }
classC.prototype.getName=function(){return this.name;};


                
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值