文章目录
- 1.构造函数
- 1-1.使用构造函数面向对象
- 1-2.构造函数里面的原型prototype
- 1-3.对象原型__proto__
- 1-4.constractor构造函数
- 1-5.构造函数、实例、原型对象三者之间的关系
1.构造函数
1-1.使用构造函数面向对象
- ES6之前对象的公共部分,不是使用类解决的,而是使用构造函数来创建对象的公共部分
- 使用构造函数会有一个问题,就是创建实例对象的时候,如果构造函数里面有方法,创建多少个实例对象,就会在内存里开辟多少个地址用来存储方法
- 用console.log(lq.say === wy.say);来证明实例对象的方法不一样,等于false,因为他们方法的地址不一样
function Star(name,age){this.name = name this.age = agethis.say = function (){console.log('hello');}}const lq = new Star('lq',22)const wy = new Star('wy',22)lq.say()wy.say()console.log(lq.say === wy.say);</script>
1-2.构造函数里面的原型prototype
- prototype就是用来解决构造函数创建实例对象时,方法的存储地址的问题
- prototype用来共享构造函数里面的方法
function Star(name,age){this.name = name this.age = age}Star.prototype.say = function(){console.log('hello');}const lq = new Star('lq',22)const wy = new Star('wy',22)lq.say()wy.say()console.log(lq.say === wy.say);
方法存到构造函数的prototype中,创建实例对象的时候就会共享原型prototype里的一个方法
1-3.对象原型__proto__
- 为什么lq实例对象能访问到prototype上的say方法,因为lq这个实例对象有一个__proto__对象原,指向的就是Star 的prototype
- proto 等价于 prototype 但是__proto__不能拿来赋值等使用
1-4.constractor构造函数
- 如果说我们修改了原来的原型对象 ,给原型对象赋值了一个对象,这个时候就要用constractor指向原来的构造函数
function Star(name,age){this.name = name this.age = age}// Star.prototype.say = function(){// console.log('hello');// }// Star.prototype.sing = function(){// console.log('sing');// }Star.prototype = {// costractor:Star,say:function(){console.log('hello')},sing:function(){console.log('sing')}}const lq = new Star('lq',22)const wy = new Star('wy',22)lq.say()wy.say()console.log(lq.__proto__);console.log(Star.prototype);
用对象来封装prototype的方法后,在log__proto__或者prototype得到的就是一个对象,并且里面没有constactor构造函数
Star.prototype = {// costractor:Star,say:function(){console.log('hello')},sing:function(){console.log('sing')}}
在封装的对象里面使用constractor指向我们构造函数后,log出来的对象里面就有constractor了