【 Javascript 】自學筆記(二)

1.  var snoopy = new Object(){  snoopy.species = "beagle", snoopy.age = 10 };
     var species = snoopy.species;
     var age = snoopy["age"];         => 兩種取值的方式

2.  function和物件宣告的方式差別的地方:
     function:
                   function Person (job, age) {
                                 this.job = "student";        
                                 this.age = 20;  }             =>在function裡的key都是用分號分開的
     Object:
                   var james = {
                                 job: "student",
                                 age: 30   }                =>在object裡的key是用逗號分開的


3.  在function裡加入function的使用方法
     function Person(job, age) {
                   this.job = job;
                   this.age = age;
                   this.speak = function() {  console.log("Hello!") ;}; }  =>在function裡宣告function
   
     var test = new Person("programmer", 30);  =>先宣告出一個新的Person物件
     test.speak();   => 呼叫person物件裡的speak function

4.  typeof 的用法: 回傳宣告的變數的型態
           var james = { name:"James" };   => console.log( typeof james ) 輸出Object
           var name = "James";  => console.log( typeof name);  輸出string

5. hasOwnProperty的用法: 若是object裡有的key,則回傳true,若是沒有的key則回傳falsse
     var myObj = { name:"Ryan" }
     console.log(myObj.hasOwnProperty("name"));   =>記得傳入的key需要代雙引號,回傳 true
     console.log(myObj.hasOwnProperty("nickname"));  =>物件裡沒有nickname的key,故回傳false

6. prototype : 在原始的物件裡新增funciont
// the original Animal class and sayName method
function Animal(name, numLegs) {   =>原始物件
    this.name = name;
    this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {   =>在 animal物件裡新增function
    console.log("Hi my name is " + this.name);
};

// define a Penguin class
function Penguin(name){  => 新的物件
    this.name = name;
    this.numLegs = 2;
}

// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();   => 在penguin物件裡新增一個key繼承原始物件
penguin = new Penguin("Ryan");  =>再產生一個新物件繼承Penguin物件
penguin.sayName(); =>可以直接操作原始物件裡的function

留言

這個網誌中的熱門文章

【 Android 】控制ImageView大小&位置

【 Android 】利用file取得資料夾內檔案

【 Android 】防止系統進入休眠和螢幕恆亮