原型&原型链
每一个函数都有一个prototype属性,prototype指向一个Object空对象(即函数原型对象),这个Object空对象里默认存在一个属性constructor-指向这个函数。
//爸爸
function Father (name) {
//给孩子命名
this.name = name;
//爸爸愿意交给儿子的技能;得到想钓上来的鱼
this.goFishing = function (fis) {
return fis;
};
};
//造儿子
let Xiaoming = new Father ('小明');
console.log(Xiaoming.name); //小明
console.log(Xiaoming.goFishing ('小章鱼'));//小章鱼
console.log(Xiaoming);
Father.prototype.cook = function () {
['章鱼烧','米饭','紫菜汤'].forEach(i => console.log(i));
}
Xiaoming.cook();//章鱼烧 米饭 紫菜汤
Xiaoming//Father {name: "小明", goFishing: ƒ};__proto__:...;//隐含属性
小明不会做饭,因为他没有这个技能,但是爸爸有啊。如果在小明的原型中找不到cook就会到proto隐式原型里也就是Father.peototype原型(即构造他的函数)里找.cook,这里找到了cook。如果在Father.prototype里没找到cook就会继续到Father.proto也就是Object.prototype(即构造他的函数)中查找cook。如果还找不到就是返回一个错误。这一样一层一层的向上查找就形成了原型链。
prototype中的constructor属性
Father.prototype//say: ƒ ();constructor: ƒ Father(name);__proto__: Object
Xiaoming//Father {name: "小明", goFishing: ƒ}
Xiaoming.__proto__//即Father.prototype
打印一下Xiaoming.constructor显示的结果是Father
Xiaoming.constructor
/*ƒ Father (name) {
//给孩子命名
this.name = name;
//爸爸愿意交给儿子的技能;得到想钓上来的鱼
this.goFishing = function (fis) {
return fis;
};
}*/
在默认情况下,所有的原型对象都会自动获得一个 constructor(构造函数)属性,这个属性(是一个指针)指向 prototype 属性所在的函数(Person)
儿子在出生的时候就会附上祖辈的技能constructor,这个属性会让孩子知道谁是自己的爸爸。我的理解是constructor是儿子天生的技能,这个技能从他的父辈就是爸爸那会一直往上传承下来。儿子可以不用DNA鉴定就知道谁是我的亲爸爸。但是这技能是不在XIaoming里的,他是在Xiaoming.proto就是爸爸的Father.prototype中的,所以实际上这个技能不是儿子实际会的,只是爸爸告诉他该怎么找的。
//造女儿
let Xiaohong = new Father('小红');
Xiaoming.constructor === Xiaohong.constructor //true
是同一个父亲
Xiaoming.__proto__//Father
上面说到constructor不是小明实际会的而是父亲告诉小明怎么做的。怎样才能让小明实际上拥有这个技能?只要让小明把这个父亲的属性继承下来,那么小明也就拥有了这个技能。
Xiaoming.prototype = new Father;
牛逼!精辟!
𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒𓃒🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺