天天看點

JavaScript學習總結1

/***我是切割線 的開始***/

 //利用prototype屬性能夠加入公有屬性和方法
   function myConstructor2(){
      this.a='大灰狼';
    };  //聲明構造函數,能夠使用對象字面量文法來向prototype屬性中加入全部公有成員

    myConstructor2.prototype={
     propertyA: 'sha' ,
     propertyB: 'feng' ,
     methodA:function(){
      alert(this.propertyA);
     },
     methodB:function(){}
    }

   var myconstrustor=new myConstructor2(); //聲明對象
    //alert(myconstrustor.methodA());
 var myconstrustor1=new myConstructor2(); //聲明對象
 var myconstrustor2=new myConstructor2(); //聲明對象
  alert("原型類測試結果="+(myconstrustor1.propertyB === myconstrustor2.propertyB));

  alert("構造函數測試結果="+(myconstrustor1.a === myConstructor2.a));

 /***我是切割線 的結束***/


function member(name, sex) {
  this.name = name;
  this.sex = sex;
  this.display = display;
}

function display() {
  var str = this.name + "是" + this.sex;
  document.write("<LI>" + str);
}
var papa = new member("楊宏文", "男生");
var mama = new member("黃雅玲", "女生");
var doggy = new member("奇 奇", "寵物狗");

papa.display();
mama.display();
doggy.display();

/*




*/      

總結

     1. 在構造函數中定義的屬性。每一個執行個體都有一個副本,互不影響。可是在prototype上定義的屬性,在全部的執行個體中共享同一個屬性。對屬性的改變會影響到全部的執行個體。

    從上面總結的觀點來看。假設要模拟面向對象,那麼屬性最好定義在構造函數中,而方法最好定義在prototye中,否則每一個執行個體的方法都占領一塊記憶體,太浪費了。

     2.從上面知道了Js中也有執行個體屬性也有靜态屬性。但終于的目的是為了更好的了解Js中的繼承,根據面向對象的思想,我們定義一個類,是為了執行個體化,使執行個體能夠調用類中定義的屬性、方法。是以能夠這麼說除非為了共享一個全局屬性,普通情況下我們都應該定義執行個體屬性、方法,這樣類的執行個體就能夠進行各種調用操作。承上啟下,從源代碼能夠看出定義執行個體屬性有2中方式,一種定義在構造函數中,一種是構造函數的prototype上,究竟應該使用哪一種呢。或者那種方式更好?

4.能夠總結出幾條規律:

1:當執行個體本身定義了屬性。使用本身屬性(能夠使用hasOwnProperty進行推斷);

2:假設執行個體本身未定義。就到構造函數中去找;

3:假設構造函數也沒有,就到構造函數的prototype的執行個體對象上去找。

4:假設prototype的執行個體對象沒有,就到其構造函數去找;

5:如此反複,一直到跟對象object中,沒找到就報undefined錯誤。

繼續閱讀