日期:2014-05-16  浏览次数:20350 次

js的对象的原型方式

//原型方式-->重点prototype(是Object拥有的一个属性,因此所有的对象都拥有这个属性)创立对象
  //此种方式建立对象不能传递参数,因为该构造函数体内是个空的。
  function Dog(){}
  Dog.prototype.name = "小毛";//属性值还可以是数组
  Dog.prototype.age = 21;
  Dog.prototype.get = function(name, age)
  {
   this.name = name;
   this.age = age;
   document.write("name:" + this.name + " , "+ "age:" + this.age );
  }
  //new Dog().get("野兽",24);
  //另外一种用原型建立对象
  function Cat(){}
  Cat.prototype.name = new Array();
  Cat.prototype.age = 3;
  Cat.prototype.get = function()
  {
   document.write("name: " + this.name + " , " + "age:" + this.age,"<br/>");
  }
  var cat1 = new Cat();
  cat1.name.push("张三");
  cat1.name.push("李四");
  cat1.age = 1;
  cat1.get();
  var cat2 = new Cat();
  cat2.get();
  //age是Number类型,是原型,它的值改变只是它的副本,并不会改变它本省。但是name是数组类型的,它是引用类型,所以它的值会改变它本省。

 

//使用原型和构造函数的方法构建对象
  //好处:即可共享原想对象中的方法,又可以通过构造方法建立对象的不通的属性,一举两得。
  function Person(name, age)
  {
   this.name = name;
   this.age = age;
  }
  Person.prototype.get = function()
  {
   document.write("name:"+this.name+" , "+"age:"+this.age);
  }
  //new Person("曹欢",21).get();
  
  //动态原型构造对象
  //这种构造出来的对象的属性值可以改变,但是方法却只实例化一次(用flag标志来确定)
  function Dog(name, age)
  {
   //static sex = "男";
   this.name = name;
   this.age = age;
   //alert(typeof Dog.asd == 'undefined');
   if(typeof Dog.flag == "undefined")
   {
    alert("值执行了一次");
    Dog.prototype.get = function()
    {
     document.write("name:"+this.name+" , age"+this.age);
    }
    Dog.flag = true;
    //alert(Dog.flag);
   }
  }
  
  var d1 = new Dog("小紫",21);
  var d2 = new Dog("小花",22);
  //d1.get();
  //d2.get();