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

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

  • 相关阅读:
    Qt 多线程使用moveToThread
    FFmpeg下载地址
    选择排序
    数据结构和算法之时间复杂度和空间复杂度
    嵌入式动态库查看需要的依赖库
    Q_UNUSED 的使用
    php对csv文件的读取,写入,输出下载操作
    python一个简单的登录
    python的反射
    python类的特性
  • 原文地址:https://www.cnblogs.com/yangjingqi/p/4337602.html
Copyright © 2011-2022 走看看