JavaScript Inheritance All in One
constructor inheritance
prototype chain inheritance
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-07-23
* @modified
*
* @description prototype chain inheritance
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
*/
const log = console.log;
function Parent(name) {
this.name = name || Parent.name;
this.language = "Chinese";
this.getName = function() {
return this.name;
}
this.setName = function(name) {
this.name = name;
return this.name;
}
}
// function Child(name) {
// // 構造函數, 繼承
// Parent.call(this, name);
// }
function Child() {
// 原型鍊, 繼承
}
/*
執行個體的屬性 __proto__ 指向 構造函數的 prototype 原型對象
構造函數的屬性 prototype 指向 構造函數的 prototype 原型對象
構造函數的 prototype 原型對象的 constructor 指向構造函數本身
*/
// 改變 prototype 與 prototype.constructor 的指向
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const p = new Parent(`p`);
const c = new Child(`c`);
log(`p.language`, p.language)
log(`c.language`, c.language)
// bug ❌ 每個執行個體都是一個獨立的對象, 執行個體之間是互相隔離, 不能動态的複用共同的屬性和方法
Parent.language = "ZH-Hans";
Child.language = "ZH-Hans";
log(`p.language`, p.language)
log(`c.language`, c.language)
/*
優點:
很好的實作了方法的共享;
缺點:
正是因為什麼都共享了, 是以導緻一切的屬性都是共享的, 隻要某一個執行個體進行修改, 那麼所有的屬性都會變化;
*/
combination inheritance
parasitic inheritance
parasitic combination inheritance
ES6 class inheritance
refs
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
©xgqfrms 2012-2020
釋出文章使用:隻允許注冊使用者才可以通路!
xgqfrms