//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;};