JavaScript Inheritance All in One_inheritance

JavaScript Inheritance All in One



JavaScript Inheritance All in One

constructor inheritance


prototype chain inheritance

JavaScript Inheritance All in One_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