zoukankan      html  css  js  c++  java
  • 简单原型语法和原型动态性

    一、简单原型语法

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

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

  • 相关阅读:
    Eureka的使用
    自定义类加载器
    继承
    Active Objects模式
    Future设计模式
    mysql备份与还原
    多生产者多消费者(第一种方式),基于synchronized,wait,notifyAll
    自己实现阻塞队列(基于数组)
    linux定时任务每隔5分钟向文本追加一行
    自己实现CountDownLatch
  • 原文地址:https://www.cnblogs.com/yangjingqi/p/4337602.html
Copyright © 2011-2022 走看看