物件原型 原型鏈 原型繼承 constructor屬性
阿新 • • 發佈:2022-11-29
原型:
每個建構函式身上都有一個prototype原型 原型身上有一個物件
被稱為原型物件 (建構函式的this和原型上的this都指向例項化物件)
形成鏈式結構被稱為原型鏈
<body>
<script>
function Star() {}
Star.prototype.sing = function () {
console.log("哈哈哈");
};
// 原型物件
console.log(Star.prototype);
const ldh = new Star();
console.log(ldh);
// __proto__
// 所有的例項化物件都有__proto__屬性指向建構函式的原型物件
console.log(ldh.__proto__ === Star.prototype); // true
</script>
</body>
原型鏈:
(建構函式通過new例項化 每個例項化身上都有一個prototype這個原型)
每個原型物件身上都有一個 __proto__這個原型 而這個物件身上也有原型物件
這個物件身上有一個consturct屬性 這個屬性指向建構函式 ,
建構函式身上也有__proto__這個原型 這個原型身上也有原型物件 就這樣一層層// function Father() {
// this.sing = function () {
// console.log("我是父級");
// };
// }
// Object原型物件
// Object.prototype.sing = function () {
// console.log("我和我的祖國");
// };
// Father.prototype.sing = function () {
// console.log("青花瓷");
// };
// const zjl = new Father();
// zjl.sing(); //例項化後呼叫方法
// 先自己原型上找到我是父級 =>青花瓷=>我和我的祖國
// console.log(Object.prototype); //construct屬性一系列
// console.log(Object.prototype.__proto__); //null
總結:訪問原型: 訪問原型上的的方法時 先訪問自己的原型上的
如果沒有則向外層找 原型上也找不到就返回null
原型繼承:
1.可以簡單理解為 一個公共的原型方法 如果想要繼承 就需要將原型物件的例項化物件
(也可以理解為父級的例項化物件)給到自己的原型物件
2.再將construct重新指向自己的建構函式
繼承父元素
// function Father(money, car, house) {
// this.money = money;
// this.car = car;
// this.house = house;
// }
// Father.prototype.hight = function () {
// // console.log("183");
// };
// let res = new Father("10000000", "保時捷711", "別墅"); //進行例項化
// console.log(res);
// res.hight();
// // Son的建構函式
// function Son() {}
// let res1 = new Son();
// // 原型繼承
// Son.prototype = new Father();
// console.log(Son.prototype); //{money: undefined, car: undefined, house: undefined}會被父級例項化物件覆蓋
// new Son().hight(); //183
// // 把建構函式從新指向自己
// Son.prototype.constructor = Son;
// console.log(Son.prototype); //此時父級中的constructor屬性上會 f son()這個建構函式(constructor用於判斷原型上的屬性上是否包含某個建構函式 多用於區分)
constructor屬性 (construtor這個屬性指向建構函式)
<body>
<script>
// constructor 單詞 建構函式
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sing = function () {
console.log("唱歌");
};
const lw = new Person("哄哄", 3);
lw.sing();
console.log(Person.prototype.constructor);
//
function Pig(one, two) {
this.one = one;
this.two = two;
}
Pig.prototype.sing = function () {
console.log("哼哼");
};
const zz = new Pig("鬧鬧", 7);
zz.sing();
console.log(Pig.prototype.constructor);
console.log(Pig.prototype.constructor === Pig);
// 如果有多個建構函式 列印它的原型 則分不出那個是自己的屬性(Person.prototype)
// 總結 所有的原型物件都有一個屬性 constructor 這個屬性指向建構函式 由此找到建構函式 可以進行區分
</script>
</body>