es6實現的繼承代碼:es6
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);
複製代碼
代碼裏有兩條原型鏈bash
// 一、構造器原型鏈
Child.__proto__ === Parent; // true
Parent.__proto__ === Function.prototype; // true
Function.prototype.__proto__ === Object.prototype; // true
Object.prototype.__proto__ === null; // true
// 二、實例原型鏈
child.__proto__ === Child.prototype; // true
Child.prototype.__proto__ === Parent.prototype; // true
Parent.prototype.__proto__ === Object.prototype; // true
Object.prototype.__proto__ === null; // true
複製代碼
ES6 extends 繼承,主要就是app
new
、Object.create
和`Object.setPrototypeOf來實現,那麼咱們能夠來實現es5的繼承// ES5 實現ES6 extends的例子
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){
// 至關於super
Parent.call(this, name);
this.age = age;
}
// new
function object(){
function F() {}
F.prototype = proto;
return new F();
}
function _inherits(Child, Parent){
// Object.create
Child.prototype = Object.create(Parent.prototype);
// __proto__
// Child.prototype.__proto__ = Parent.prototype;
Child.prototype.constructor = Child;
// ES6
// Object.setPrototypeOf(Child, Parent);
// __proto__
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);
複製代碼
上述兩中實現繼承的方式都是經過 [[Prototype]] 機制來實現的,咱們能夠使用對象關聯的風格來實現上述功能函數
Parent = {
init: function(value){
this.name = value
},
sayHello: function(){
console.log('hello');
},
sayName: function(){
console.log('my name is ' + this.name);
return this.name;
}
}
Child = Object.create( Parent );
Child.sayAge = function(){
console.log('my age is ' + this.age);
return this.age;
}
var child1 = Object.create( Child );
child1.init( "tom" );
var child2 = Object.create( Child );
child2.init('lili');
child1.sayHello();
child2.sayName();
複製代碼
從上面代碼能夠看出對象關聯風格的代碼顯然更加簡潔,由於這種代碼只關注一件事:對象之間的關聯關係, 使用類構造函數的話,你須要在同一個步驟中實現構造和初始化。然而,在許多狀況下把這兩步分開(就像對象關聯代碼同樣)更靈活。 對象關聯除了能讓代碼看起來更簡潔(而且更具擴展性)外還能夠經過行爲委託模式簡化代碼結構ui