the way javascript create objects

//第一种,直接创建实例
1 var dada = new Object();
2 dada.job = "worker";
3 dada.married = true;
//替代语法(使用对象 literals)
1 var james = {
2     // add properties to this object!
3     job : "programmer",
4     married : false    
5 };

//第三种

//使用对象构造器
 1 //function star (name,age,area) {
 2     var star = function(name,age,area) {
 3     //var a = function star (name,age,area) {
 4         //上面的语句相当于var star = function(name,age,area) {
 5         //也可以是var a = function star (name,age,area) {,但是这样的话下面创建新对象实例的时候就要用a
 6         this.name = name;
 7         this.age = age;
 8         this.area = area;
 9         this.birthday = function (){
10             //return 2013 - this.age;
11             //this.birth = 2013;
12             this.birthday =2013- this.age;
13         };
14     }

//一旦您有了对象构造器,就可以创建新的对象实例

 1 var prince = new star("yujianqi",26,"zhejiang");
 2     //var prince = new a("yujianqi",26,"zhejiang");
 3     prince.birthday();
 4     pname = "my name is" + "" + prince.name +", and my birthday is" + "" +prince.birthday +".";
 5     alert(pname);
 6     var baby = new star("baby",5,"beijing");
 7     //您可以通过为对象赋值,向已有对象添加新属性
 8     baby.married = true;
 9     baby.birthday();

//JavaScript for...in 语句循环遍历对象的属性。注释:for...in 循环中的代码块将针对每个属性执行一次。

1 for(a in baby){
2         //alert(baby[a]);
3         //alert(a);
4     }

 

你可能感兴趣的:(JavaScript)