重新复习了一遍js的继承,代码为自己手敲,如有错误请指正
ES6 extends 继承做了什么操作
class Parent{
constructor(name){
this.name = name;
}
static sayHello(){
console.log('hello')
}
sayName(){
console.log('my name is' + this.name)
return this.name;
}
}
class Child extends Parent{
constructor(name, age){
super(name);
this.age = age
}
sayAge(){
console.log('my age is ' + this.age)
return this.age;
}
}
let parent = new Parent('Parent');
let child = new Child('Child', 18);
//构造器原型链
Child.__proto__ = Parent
Parent.__proto__ = Function.prototype
Function.prototype.__proto__= Object.prototype
Object.prototype.__proto__ = null
//实例原型链
child.__proto__ = Child.prototype
Child.prototype.__proto__ = Parent.prototype
Parent.prototype. __proto__ = Object.prototype
Object.prototype.__proto__ = null
ES6 extends 继承,主要就是:
- 1.把子类构造函数(Child)的原型(proto)指向父类构造函数(Parent).
- 2.把子类实例child的原型对象(Child.prototype)的原型(proto)指向父类parent的原型对象(Parent.prototype)
- 3.子类构造函数Child继承了父类构造函数Parent里的属性,使用super调用的(ES5使用call或者apply调用传参)
什么可以设置__proto__链接 设置 proto new、Object.crecte和Object.setPrototypeOf可以设置__proto__ new 做了什么
- 1、创建了一个全新的对象。
- 2、这个对象会被执行 [[Prototype]](也就是 proto)链接。
- 3、生成的新对象会绑定到函数调用的 this。
- 4、通过 new创建的每个对象将最终被 [[Prototype]]链接到这个函数的 prototype对象上。
- 5、如果函数没有返回对象类型 Object(包含 Functoin, Array, Date, RegExg, Error),那么 new表达式中的函数调用会自动返回这个新的对象。
Object.create:ES5提供的
Object.create(proto,[propertiesObject]) 方法创建一个新对象,使用现有的对象来提供新创建的对象的 proto。 它接收两个参数,不过第二个可选参数是属性描述符(不常用,默认是 undefined)。对于不支持 ES5的浏览器, MDN上提供了 ployfill方案:MDN Object.create() // 简版:也正是应用了new会设置__proto__链接的原理。
if(typeof Object.create !== 'function'){
Object.create = function(proto){
function F() {}
F.prototype = proto;
return new F();
}
}
ES5实现(寄生组合式继承)
function Parent(name){
this.name = name;
}
Parent.sayHello = function(){
console.log('hello')
}
Parent.prototype.sayName = function(){
console.log('my name is ' + this.name);
return this.name
}
function Child(name, age){
Parent.call(this, name)
this.age = age;
}
//new
function object(){
function F(){}
F.prototype = proto;
return new F();
}
function _inherits(Child, Parent){
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.__proto__ = Parent;
}
_inherits(Child, parent)
Child.prototype.sayAge = function(){
console.log('my age is' + this.age)
return this.age
}
var parent = new Parent('Parent')
var child = new Child('Child', 18)
console.log('parent:' parent); //parent: Parent{name: "Parent"}
Parent.sayHello(); //hello
parent.sayName(); //my name is Parent
console.log('child:', child); //child: Child{name: "Child", age:18}
Child.sayHello(); //hello
child.sayName(); //my name is Child
child.sayAge(); //my age is 18
继承对于JS来说就是父类拥有的方法和属性、静态方法等,子类也要拥有。
- 1.子类中可以利用原型链查找,
- 2.也可以在子类调用父类,
- 3.或者从父类拷贝一份到子类等方案。
- 继承方法可以有很多,重点在于必须理解并熟。
回顾寄生组合式继承,主要就是三点:
- 1.子类构造函数的 __proto__指向父类构造器,继承父类的静态方法
- 2.子类构造函数的 prototype的 __proto__指向父类构造器的 prototype,继承父类的方法。
- 3.子类构造器里调用父类构造器,继承父类的属性。