js继承(es5和es6)
2021-03-08 06:29
标签:targe push 开发 pre 参数 cti es6 对象 实例 js继承(es5和es6) 标签:targe push 开发 pre 参数 cti es6 对象 实例 原文地址:https://www.cnblogs.com/yaya-003/p/12876984.html es5的继承
1.原型链继承 缺点:创建实例时不能传递参数,所有属性都被实例共享
function Parent() {
this.name = ‘kevin‘;
}
Parent.prototype.getName = function () {
console.log(this.name);
}
function Child() { }
Child.prototype = new Parent();
var child = new Child();
child.getName() //kevin
2.借用构造函数
优点:可以传递参数,避免了引用类型共享
缺点:方法都在构造函数中定义,每次创建实例都会创建一遍方法。
function Parent() {
this.name = [‘kevin‘];
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
var child1 = new Child();
var child2 = new Child();
child1.name.push("cc");
3.组合继承
优点:融合了原型继承和构造函数继承,是JavaScript中常用的设计模式。
缺点:调用两次父构造函数
function Parent() {
this.name = [‘kevin‘];
}
Parent.prototype.getName = function () {
console.log(this.name, this.age);
}
function Child(age) {
Parent.call(this);
this.age = age;
}
Child.prototype = new Parent();
var child1 = new Child(19);
var child2 = new Child(20);
child1.name.push("cc");
child1.getName(); //["kevin", "cc"] 19
child2.getName(); //["kevin"] 20
4.原型式继承
这是es5中的,Object.create的模拟实现。
缺点:创建实例时不能传递参数,所有属性都被实例共享
function createObj(o) {
function F() { }
F.prototype = o;
return new F();
}
5.寄生式继承
function createObj(o) {
var clone = Object.create(o);
clone.say = () => { console.log(this) };
return clone
}
console.log(createObj({})); //{say: ƒ}
6.寄生组合式继承
优点:开发人员普遍认为寄生组合式继承是最理想的继承范式
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function () {
console.log(this.name, this.age);
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
var F = function () { }
F.prototype = Parent.prototype;
Child.prototype = new F();
var child1 = new Child("cc", 20)
console.log(child1) //Child {name: "cc", age: 20}
es5之后的(class本质还是函数,只是一个语法糖而已。)
1.class通过extends关键字实现继承。
class Parent {
constructor(x, y) {
this.x = x;
this.y = y
}
}
class Child extends Parent {
constructor(x, y, name) {
super(x, y);//调用父类的constructor(x,y)
this.name = name;
}
}
var child1 = new Child("x", "y", "ccg");
console.log(child1); //Child {x: "x", y: "y", name: "ccg"}
2.super关键字
class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();
}
}
new A();
new B();
class Parent {
static myMethod(msg) {
console.log(‘static‘, msg);
}
myMethod(msg) {
console.log(‘instance‘, msg);
}
}
class Child extends Parent {
static myMethod(msg) {
super.myMethod(msg);
}
myMethod(msg) {
super.myMethod(msg);
}
}
Child.myMethod(1); //static 1
var child = new Child();
child.myMethod(2); //instance 2
class Parent {
constructor() {
super();
console.log(super);//报错
}
}