OnlyTheStrongSurvive

JS创建对象

上一篇 / 下一篇  2011-08-25 16:56:39 / 个人分类:单元测试

1.       利用函数创建对象(构造函数)

function User(id,name,birth)

{

   this.id = id;

   this.name = name;

   this.birth = birth;

   this.sayHello = function(str){

      print("hello "+str)

   };

}

var user = new User(1,'Tom',new Date());

user.sayHello("Tom");

print(user.id);

print(user["name"]);

print(user.birth);

 

2.  利用原型创建对象(原型法)

var user = new Object();

user.id = 1;

user.name='lisi';

user.birth=new Date();

user.score = 200;

user.fun = function(){

  print(this.name+this.birth);

};

 

user.fun();

print(user.name);

 

3.  利用常量法来创建对象。

var user = {

  id:15,

  name:'first',

  birth:new Date(),

  sayHello:function(){

    print(this.name);

  }

};

 

user.name="second";

user.sayHello();

delete user.name;

user.sayHello();


TAG:

 

评分:0

我来说两句

Open Toolbar