JS高级---原型

原型

作用1 :节省空间,数据共享

function Person(name,age){
    this.name=name;
    this.age=age;
}//通过自定义构造函数来创建对象
Person.prototyp e.eat=function(){
    console.log("我爱js");
}//通过原型来添加方法
var p1=new Person("小明",20);
var p2=new Person("小红",30);
console.log(p1.eat==p2.eat);//true
  1. 构造函数,实例对象,原型对象总结

    • 通过构造函数来实例化对象
    • 构造函数中有一个属性叫做prototype,是构造函数的原型对象,并且这个原型对象中有一个构造器constructor,这个构造器就是指向自己所在的原型对象的构造函数
    • 实例对象的原型对象(proto)
  2. 通过原型和局部变量变全局变量来实现产生随机数对象

    <!DOCTYPE html>
    <html>
    <head>
    	<title></title>
    </head>
    <body>
    	<script>
    		(function(win){
    			function Random(){
    
    			};//产生随机数的构造函数
                
    			Random.prototype.getRandom=function(min,max){//向构造函数中添加方法
    				return Math.floor(Math.random()*(max-min)+min);//获得的随机数范围在min到max之间(包括min,不包括max)
    			};
                
    			win.Random=Random;//将构造函数Random赋予给window对象,变成全局对象
    		})(window)//window是实参,win是形参
            
            //外部调用
    		var ram=new Random();//实例化
    		console.log(ram.getRandom(5,100));
    	</script>
    </body>
    </html>
    

posted on 2018-10-07 22:42  xiao545  阅读(123)  评论(0编辑  收藏  举报

导航