js的對象的原型方式

來源:互聯網
上載者:User

//原型方式-->重點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();


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.