码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-03-14 16:36:47      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

一、简单原型语法

            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();//错误 

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

 

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

标签:

原文地址:http://www.cnblogs.com/yangjingqi/p/4337602.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!