日期:2014-05-16 浏览次数:20399 次
// 定义一个最简单的类 function Person(){ //这里相当于一个构造函数,是不是很像Java中的构造方法。 } //新建一个类 var person = new Person(); //动态给这个类添加属性(同样也可以修改属性) person.id = "001"; person.name = "zhang"; //动态给对象添加方法(同样也可以修改这个方法),可以将它看成两部分,就是将一个函数体赋给一个变量,通俗的理解。 person.print = function(){ alert("id:" + this.id + " name:" + this.name); } //删除person对象属性 person.id = undefined; person.name = undefined; //删除person的方法 person.print = undefined;
//创建无类型对象,这里使用json的语法 var obj1 = {}; var obj2 = { ID: 1, Name: "Johnson", //定义一个函数 showMessage: function(){ alert("ID: " + this.ID + "Name: " + this.Name); } }
//综合演示js中类和属性的动态添加 var life = {}; for(life.age = 1; life.age <= 3; life.age++) { switch(life.age) { case 1: life.body = "卵细胞"; life.say = function(){alert(this.age+this.body)}; break; case 2: life.tail = "尾巴"; life.gill = "腮"; life.body = "蝌蚪"; life.say = function(){alert(this.age+this.body+"-"+this.tail+","+this.gill)}; break; case 3: delete life.tail; delete life.gill; life.legs = "四条腿"; life.lung = "肺"; life.body = "青蛙"; life.say = function(){alert(this.age+this.body+"-"+this.legs+","+this.lung)}; break; }; life.say(); };