为了减少内存使用率可以使用原型对象
<script>//构造函数 公共的属性和方法 封装到Star 构造函数里面了//公共的属性写到 构造函数里面function Star(uname,age){this.uname=unamethis.age=agethis.sing=function(){console.log('唱歌');}}const ldh=new Star('刘德华',18)const zxy=new Star('张学友',19)console.log(ldh === zxy)//falseconsole.log(ldh.sing === zxy.sing)//false//上面两个都是false也就是意味着每一个实例都会分配内存空间function Animal(uname,age){this.uname=unamethis.age=age}//公共的方法写到原型对象里面Animal.prototype.eat=function(){console.log(this.uname+'都要吃饭');}dog=new Animal('dog',5)dog.eat()tiger=new Animal('tiger',10)console.log(dog.eat===tiger.eat);</script>
原型自定义方法
<script>//自己定义 数组扩展方法 求和 最大 最小值//1.我们定义的这个方法 任何一个数组实例对象都可以使用//2.自定义的方法写到 数组.prototype身上const arr= new Array(1,2,3);console.log(arr);//自定义的方法...可以给我们展开Array.prototype.max=function(){//原型函数里面的this指向的是 实例对象arrconsole.log(this);return Math.max(...this)};console.log(...arr);result=arr.max()console.log(result);//自定义加法方法求和Array.prototype.sum=function(){return this.reduce(function(prev,item){return prev+item},0)};console.log(arr.sum());//自定义方法求最小值Array.prototype.min=function(){return Math.min(...this);}console.log(arr.min());</script>
结果:
<script>//constructor 单词 构造函数function Star(){}// Star.prototype.sing=function(){// console.log('唱歌');// }// Star.prototype.dance=function(){// console.log('跳舞');// }console.log(Star.prototype.constructor===Star);console.log(Star.prototype);Star.prototype={sing:function(){console.log('唱歌');},dance:function(){console.log('跳舞');}}console.log(Star.prototype);Star.prototype={constructor:Star,sing:function(){console.log('唱歌');},dance:function(){console.log('跳舞');}}console.log(Star.prototype);</script>
结果:
<script>//对象都会有一个属性__proto__指向构造函数的prototype原型对象,之所以我们对象可以使用构造函数prototype//原型对象的属性和方法,就是因为对象有__proto__原型的存在function Star(){}const ldh=new Star();console.log(ldh.__proto__===Star.prototype);</script>
只要是对象就就有__proto__
只要有原型对象就有constructor