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

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

  • 相关阅读:
    程序员掌握的单词汇总
    Django--基础补充
    C#入门概述
    python常用模块
    软件开发经验之谈
    p7.BTC-挖矿总结
    p6.BTC-挖矿难度
    p5.BTC-网络
    p4.BTC-实现
    p3.BTC-协议
  • 原文地址:https://www.cnblogs.com/yangjingqi/p/4337602.html
Copyright © 2011-2022 走看看