1、原型链继承
2、原型式继承
3.圣杯模式
4、非标准模式
5、自定义
6、构造函数继承(对象冒充继承)
7、组合继承(原型链+构造函数)
8、寄生组合继承
一、原型链继承
function Person(name, age) { this.name = name; this.age = age; } function sayHi() { this.age = '20'; //sayHi通过原型继承了Person,形成了链条 } sayHi.prototype = new Person('lydia', 15); var Person = new sayHi(); // console.log(Person.age);
二、原型继承
// 二、原型继承 原型上会污染 function Father() {} Father.prototype.firstName = '琳达'; function Son() {} //儿子的原型指向父亲 Son.prototype = Father.prototype; Son.prototype.age = 10; var son = new Son(); var father = new Father(); father.name = '爱德华';
三、圣杯模式
// 4、圣杯模式 function Father() {} Father.prototype.firstName = '琳达'; function Son() {} function Temp() {} //son的原型链上有father.prototype var inhert = (function(Target, Origin) { // 定义一个空对象 function F() {} return function(Target, Origin) { // 让f指向father F.prototype = Origin.prototype; // target原型指向f,到这里会发现都指向了father Target.prototype = new F(); Target.prototype.constructor = Target; Target.prototype.uber = Target.prototype; } })(); // son的原型链上有father.prototype 且不会造成原型链污染 inhert(Son, Father); Son.prototype.age = 21; var son = new Son(); console.log(son.__proto__.constructor);
四、非标准模式继承
// 2.第二种继承方式 非标准 // 用户 vip用户 money function User(uName, uAge, uSex) { this.uName = uName; this.uAge = uAge; this.uSex = uSex; } User.prototype.login = function() { console.log('welcome' + this.uName); } // 编程解耦 function VIP(uName, uAge, uSex, uMoney) { User.call(this, uName, uAge, uSex); this.uMoney = uMoney; } var vip1 = new VIP('lily', 16, '女', 100);
五、自定义
function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.fullName = this.firstName + " " + this.lastName; } Person.prototype.sayHello = function() { console.log(`大家好,我叫${this.fullName},今年${this.age}岁了`) } function inherit(son, father) { // 1. 最容易理解的方式 容易造成原型的污染 因此不推荐 在son原型上添加的任何属性都会同步到father中 son.prototype = Object.create(father.prototype); // 给原型对象设置构造函数值 son.prototype.constructor = son; // 记录父类的原型 圣杯模式的兼容写法 son.prototype.uber = father; } inherit(Student, Person); function Student(firstName, lastName, age, className) { // Person(firstName, lastName, age);//this->wondow // 改变this指向 // Person.call(this, firstName, lastName, age); // Person.apply(this, arguments); // 圣杯模式中的以一种思路 this.uber(firstName, lastName, age); this.className = className; } Student.prototype.learning = function() { console.log(`我是${this.className}班的学生,正在学习前端`); } var lilei = new Student('lili', 12, '20202006');
不确定能不能跳转过去,试了好久文章转载还是不行,在这里写了这个地址,里面有几种我没写出来的继承方式
转载:https://www.cnblogs.com/LWWTT/p/11100210.html