javascript中new机制

function A(options){

    this.xx = options.xx;

}

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

一个构造函数,在原型上添加一个方法,new一个对象后,这个对象是怎么具有属性和方法的?

//创建动物类
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
    */

猜你喜欢

转载自my.oschina.net/u/3229305/blog/1784905