• 面向对象-原型


    <script type="text/javascript">
    
    		function CreatePeo(n){
    			this.name=n;
    		}
    		CreatePeo.prototype.emma="好人"//给函数对象prototype属性添加
    		,会体现在a.__proto__即在将来实例的父级得到 
    		
    		CreatePeo.prototype.show=function(){//现在就是把车给父亲,两个儿子都可以开
    			console.log(this.name)//在构造函数的prototype的方法内的this会自动指向将来new出来的实例
    		}
    		var a=new CreatePeo("admin")
    		var b=new CreatePeo("root")
    		
    		a.show()
    		b.show()
    
    		console.log(a.__proto__)//{emma: "好人", constructor: ƒ}
    		现在给函数身上添加属性,会被将来实例的父级捕捉到,考虑到就近原则,
    		现在打印a.emma就可以找到好人
    		
    		富豪有两个孩子只有一个车库,就把孩子的两辆车都卖掉,给富豪买一辆车,两个儿子轮流开;即把代买里面的show都没了
    
    		
    		console.log(a)//CreatPeo {name: "admin", show: ƒ}
    						//name: "admin"
    						//show: ƒ ()
    						//__proto__: Object
    		console.log(b)
    
    		console.log(a.show==b.show)        //true  两个人开的是同一辆车
    
    		// __proto__原型链:指向自身的父级对象
    
    		console.log(a.__proto__)//{constructor: ƒ}
    		// constructor:指针:指向自身
    
    		console.log(a.__proto__.constructor==CreatePeo)//true
    
    		console.log(a.__proto__.constructor)//ƒ CreatePeo(n){
    // 												this.name=n;
    // 												this.show=function(){
    // 													console.log(this.name)
    // 												}
    // 											}
    		console.dir(CreatePeo)//查看各种属性
    
    		console.log(CreatePeo.prototype)//{constructor: ƒ}
    
    		console.log(CreatePeo.prototype==a.__proto__)//true
    		a.__proto__的父级是构造函数的prototype属性(CreatePeo.prototype)
    		父级是一个对象,可以往父级身上添加属性
    
    
    		就近原则
    		对象访问属性或方法时,会先找自身有没有,有就执行,没有呢,直接顺着__proto__向上找寻,找到了,就执行,没找到继续向上,直到最顶层的Object对象,没有,报错
    
    		构造函数中的this和构造函数的prototype上的方法中的this,指向的都是将来new出来的实例
    
    		js中每种数据类型都有一个:__proto__:原型链:指向父级类型
    		js中一般函数都有一个:prototype:原型对象,专门用来给将来new出来的对象作为父级使用
    		
    	</script>
    
  • 相关阅读:
    ERROR: Cannot set priority of registrydns process 33740
    Hbase和Phoenix部署-单机版
    ambari安装hdp时,新建的ambari-hdp-1.repo中baseurl无值
    centos7.2升级openssh到8.0
    kafka一个broker挂掉无法写入
    对cdh搭建过程错误总结及解决方法
    streamsets
    [Spark]Task not serializable
    [Kafka]How to Clean Topic data
    Postgresql Master/Slaver
  • 原文地址:https://www.cnblogs.com/sansancn/p/10914971.html
Copyright © 2020-2023  润新知