日期:2014-05-16  浏览次数:20380 次

javascript 理解对象原型(一)

?

            //------------------------------
            //1.javascript对象创建的时候,构造函数会创建该对象的原型,对象会继承原
            //型的所有方法和属性,即每个对象都连接到一个原型对象.
            //
            //2.所有通过字面量创建的对象都连接到Object.prototype这个标准的对象.
            //
            //3.当你创建某个对象时,你可以选择使用某个对象作为他的原型
            //
            //下面创建了一个可以是对象在创建时选择自己的原型
            //------------------------------
            var stooge={
                first_name:'Hanks',
                last_name:'tom'
            }
            if(typeof Object.beget!=='function')
            {
                Object.beget = function(o)
                {
                    var F = function(){
                        this.constructor = arguments.callee
                        
                    };
                    F.prototype = o;
                    return new F();
                }
            }
        
            //创建了另一个对象,使用stooges作为原型
            var another_stooge = Object.beget(stooge);
            
            //查看对象的值
            alert(another_stooge.first_name);//output:Hanks
                
            //现在更改原型
            stooge.first_name='Jack';
            //查看原型的值
            alert(stooge.first_name); //output:Jack
            //查看对象的值
            alert(another_stooge.first_name);//output:Jack
                 
            //现在更改对象
            another_stooge.first_name='Michel';
            //查看对象的值
            alert(another_stooge.first_name);//output:Michel
            //查看原型的值
            alert(stooge.first_name);//output:Jack
            //通过继承对象访问原型上的值
            alert(another_stooge.constructor.prototype.first_name);
               
            //对原型添加新的属性
            stooge.middle_name='MoJce';
            //查看对象的值
            alert(another_stooge.middle_name);//output:MoJce
             
            //----------------------------
            //结论:对继承对象的更改并不会反应到原型上去,即更新不
            //会影响原型连接上的值
            //如果某个新的属性被添加到原型中,就会立刻反应到所有使用该原型创造的
            //对象中
            //----------------------------

            //----------------------------
            //属性检测,typeof检测手段可以检测到从原型上继承过来的属性,
            //但hasOwnProperty却忽视了原型上的属性,只检测本对象拥有的
            //属性
            //----------------------------
            alert(typeof flight01.number); //output:number
            alert(typeof stooge.first_name);//output:string
            alert(typeof another_stooge.first_name);//output:string
            alert(flight01.hasOwnProperty('number'));//output:true
            alert(another_stooge.hasOwnProperty('first_name'));//output:false