1什么是原型对象以及原型对象的作用
javaScript规定,每一个构造函数都有一个prototype属性,指向另一个对象,我们也称为原型对象,这个对象可以挂载函数,对象实例化不会多次创建原型上的函数,节约内存。
原型对象上的成员会被所有的实例对象所共享,就是当一个实例对象访问某个成员时,如果不存在会自动到原型对象上找。
构造函数和原型对象中的this都是指向实例化对象。
2构造函数 实例对象 原型对象三者的关系
构造函数.prototype 指向原型对象
// 实例对象.__proto__ 指向原型对象
// 原型对象.constructor 指向构造函数
3把方法和属性保存到原型对象上,通过实例化对象调用
Person.prototype.height=180
person.__proto__.say=function(){
console.log(111);
}
const oa=new Person('lisi',15)
console.log(oa);
oa.say() //111
console.log(oa.height); //180
</script>
4原型链是由原型对象形成的一个链条
当一个实例对象访问某个成员时,如果不存在,则会到原型对象上找
如果原型对象上也没有,则继续向上找原型对象
<body>
<script>
function Person(){
}
let p =new Person()
// 一级原型
console.log(p.__proto__);
// 一级原型对象的构造函数是Person
console.log(p.__proto__.constructor===Person); //true p.__proto__.constructor Person()构造函数
// 二级原型
console.log(p.__proto__.__proto__);//Obj
// 二级原型对象的构造函数是Object
console.log(p.__proto__.__proto__.constructor===Object); //ture
// Object构造函数对应的原型对象,是其他实例对象的二级原型对象
console.log(Object.prototype===p.__proto__.__proto__) //true
// 二级原型的原型
console.log(p.__proto__.__proto__.__proto__); //null
// 原型链是有原型形成的一个链条
</script>
</body>
5替换原型对象
<script>
function fn(n,a){
this.name=n;
this.age=a;
this.say=function(){
console.log(111);
}
}
const oa=new fn('lisi',14)
console.log(oa.name);
oa.say() //111
// 向默认的原型对象上添加成员
// 添加相同名称的方法 无法覆盖
fn.prototype.say=function(){
console.log('speak');
}
const ob=new fn('lisi2',15)
ob.say() 111 打印的还是111
//说明相同方法名称不能覆盖
// 添加不同名称的方法
fn.prototype.say1=function(){
console.log('222');
}
const oc=new fn('lisi2',15)
oc.say() //111
oc.say1() //222
// 替换整个原型对象
let obj={}
fn.prototype=obj
console.log(fn.prototype==obj); //true
let od=new fn('lisi',15)
console.log(fn.prototype);//{}
console.log(obj); //{}
od.say() //111 构造函数的方法,原型对象被空对象替换不影响
od.say1()//这个是原型对象的方法,被替换后不生效
</script>
6继承原型 主要过程把父级的实例化对象给子级的原型对象
<script>
const human=function(){
this.eyes='111'
this.nose='222'
}
const man=function(){
}
const woman=function(){
}
// human的原型对象是object
console.log(human.prototype);
// human的实例化对象
const hu =new human()
console.log(hu);
// 是把父级的实例化对象给子级的原型对象
man.prototype=hu
woman.prototype=hu
const two=new man()
console.log(two.eyes);
// const say=function(){
// console.log('speak');
// }
//添加新的成员到man成原型对象上
two.__proto__.say=function(){
console.log('speak');
}
two.say() //speak
// const four =new man
// four.say() //speak
const three=new woman()
console.log(three.eyes);
</script>
7instanceof运算符
作用:作用于判断构造函数与实例对象的关系
依据:构造函数对象的原型对象是否在以实例为起点
语法:对象instanceof函数
函数对应的原型对象是否在实例起点的原型链上,如果在原型链上
则为true
function Human(){}
function Person(){}
let oa= new Person()
console.log(oa instanceof Person); //true
console.log(oa instanceof Human); //false
console.log(oa instanceof Object); //true