从新复习了一遍js的继承,代码为本身手敲,若有错误请指正浏览器
ES6 extends 继承作了什么操做bash
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);
复制代码
//构造器原型链app
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 继承,主要就是:ui
什么能够设置__proto__连接 设置 proto new、Object.crecte和Object.setPrototypeOf能够设置__proto__ new 作了什么this
Object.create:ES5提供的spa
Object.create(proto,[propertiesObject]) 方法建立一个新对象,使用现有的对象来提供新建立的对象的 proto。 它接收两个参数,不过第二个可选参数是属性描述符(不经常使用,默认是 undefined)。对于不支持 ES5的浏览器, MDN上提供了 ployfill方案:MDN Object.create() // 简版:也正是应用了new会设置__proto__连接的原理。prototype
if(typeof Object.create !== 'function'){
Object.create = function(proto){
function F() {}
F.prototype = proto;
return new F();
}
}
复制代码
ES5实现(寄生组合式继承)code
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来讲就是父类拥有的方法和属性、静态方法等,子类也要拥有。
回顾寄生组合式继承,主要就是三点: