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

相关文章
相关标签/搜索