javascript中new機制

function A(options){app

    this.xx = options.xx;函數

}this

A.prototype.方法名 = function(){}spa

一個構造函數,在原型上添加一個方法,new一個對象後,這個對象是怎麼具備屬性和方法的?prototype

//建立動物類
function Animal(name){
    this.name = name;
}
Animal.prototype.say = function(){}

Animal.color = 'green';
Animal.prototype.toSay = function(){
    console.log(this.name + ' says....')
}

var cat = new Animal('tom');//實例化貓

console.log(
    cat.name, //tom
    cat.color //undefined
);

cat.toSay();

console.log(
    Animal.name, //Animal
    Animal.color //green
);

Animal.toSay(); // 報錯,toSay在Animal的prototype上,Animal沒有toSay()

/* 解析:
        重點在var cat = new Animal();
        1.var obj = {}; 建立一個空對象 
對象

        2.obj.__proto__ = Animal.prototype,obj的__proto__指向Animal的原型對象,繼承

        3. var result = Animal.apply(obj,arguments);調用Animal,傳遞arguments,讓obj繼承Animal的屬性原型鏈

        4. return obj,cat接受原型

           原型鏈 cat --> Animal.prototype --> Object.prototype --> null
                  Animal --> Funtion.prototype --> Object.prototype -->null
    */
io

相關文章
相關標籤/搜索