简单原型语法和原型动态性

一、简单原型语法

            function Student(){
                                
            }
            Student.prototype={
                name:'yjj',
                age:15,
                myName:function (){
                    alert(this.name);    
                    
                }                
            }
        //简单原型写法本质上完全重写了默认的prototype对象,因此construtor属性也就变成了新对象的constructor属性,指向了object构造函数,不再指向Student函数。
        //通过constructor已经无法确定对象类型了
        var student = new Student();
        alert(student instanceof Object);//true
        alert(student instanceof Student);//true
        alert(student.constructor==Student);//false
        alert(student.constructor==Object);//true 

如果constructor的值很重要,可以设置回来。

        function Student(){
                                
            }
            Student.prototype={
                constructor:Student,
                name:'yjj',
                age:15,
                myName:function (){
                    alert(this.name);    
                    
                }                
            }
         var student = new Student();
        alert(student instanceof Object);//true
        alert(student instanceof Student);//true
        alert(student.constructor==Student);//true
        alert(student.constructor==Object);//false

注意constructor属性默认是不可枚举的,但这样设置后就可以枚举了。

二、原型的动态性

可以先创建出对象,然后再对原型添加属性,之后还是能获取到原型添加的属性。

 function Student(){
                                
         }
      var student = new Student();
      Student.prototype.myName=function (){          
        alert('yjj');
      }
      student.myName();//输出yjj

注意和简单原型语法一起使用时:

function Student(){
                                
         }
      var student = new Student();
      
      Student.prototype={
                constructor:Student,
                name:'yjj',
                age:15,
                myName:function (){
                    alert(this.name);    
                    
                }                
       }
       student.myName();//错误 

简单原型写法 重写原型对象切断了现有原型与任何之前已经存在的对象实例之间的联系,它们仍然引用的是最初的原型。

 

posted @ 2015-03-14 15:12  老树昏鸦  阅读(303)  评论(0编辑  收藏  举报