從新複習了一遍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來講就是父類擁有的方法和屬性、靜態方法等,子類也要擁有。
回顧寄生組合式繼承,主要就是三點: