prototype/constructor/__proto__之prototype

时间:2021-06-08 20:24:47

1任何对象都有__proto__属性 属性值Object
2并不是所有对象都有prototype属性。只有方法对象(构造函数)以及基本数据类型还有Array,有prototype属性;并且所有方法(对象)的prototype属性都是object

在网上有很多关于原型的讲解。在这里我用console.log()的方式给大家呈现。

 //一、基本数据类型的原型
     //console.log(String) String() 这时我们可以把它理解为构造函数

     //console.log(typeof String)  function

     //console.log(String.prototype)  String {}

    //console.log(typeof String.prototype)  object 说明String的prototype属性是一个object对象,既然是对象我们就可以给他添加属性或者方法。

    String.prototype.cf=function(n){   //给String.prototype这个obj添加方法cf,字符串乘法
            return    new Array(n+1).join(this)
    }
     var str="cmf"
     //console.log(str.cf(10))  cmfcmfcmfcmfcmfcmfcmfcmfcmfcmf

     //console.log(String.prototype)   String { cf=function()} String的原型是一个对象(obj)它有cf属性,这个属性对应着一个方法。

 //二、构造函数的原型
 function Info(m,n){ //构造函数
     this.m=m
     this.n=n
     this.mn=m+"|"+n
 }
 //var 什么东西前面可以加var 基本数据类型(String Number true underfind) 或者 obj(null function Array)

 //var info=new Info('cmf','man')
 //console.log(typeof info)     object 通过构造函数实例化出来的都是obj
 //console.log(info) // info { m="cmf",  n="man",  mn="cmf|man"}

 //console.log(typeof Info) //function  前面说过方法对象(构造函数)有prototype属性

 //console.log(Info.prototype) // Info {}
 //console.log(typeof Info.prototype) //object Info.prototype属性是一个对象,是对象我们就给可以给他定义方法或者属性。

 //给构造函数原型(obj)定义方法(属性)
 Info.prototype.name=function(){
     return this.m+'name'
 }
 Info.prototype.age='18'

 var info2=new Info('cmf','man') //实例化

                       /*
                                     age:"18"在原型上
                                     m:"cmf"
 console.log(info2)                    mn:"cmf|man"
                                     n:"man"
                                     name:function()在原型上
                         */
 //console.log(info.name())
 //三 为什么只有    方法对象以及基本数据类型有prototype属性,它们两有什么相似的地方
 //第一个问题我不知道
 //第二个问题
 var str1=new String('adq')
 var str2='xhb'
 var str3='adq'
 var arry=new Array(1)
 var arry2=new Array(2)
 /*
 console.log(typeof str1) //object
 console.log(typeof str2) //string
 console.log(str1.cf(8)) //adqadqadqadqadqadqadqadq
 console.log(str2.cf(8))  //xhbxhbxhbxhbxhbxhbxhbxhb

 console.log(str1==str3) //true
 console.log(str1===str3) //false

 怎么理解呢 我们把所有的东西都理解为obj。基本数据类型理解为一个特殊的obj。

把上面的代码自己console.log一遍应该有体会了。