es6類的繼承和物件關聯

2021-09-24 07:08:38 字數 1927 閱讀 7808

es6實現的繼承**:

class parent

static sayhello

() sayname()}

class child extends parent

sayage()}

let parent = new parent('parent');

let child = new child('child', 18);

複製**

**裡有兩條原型鏈

// 1、構造器原型鏈

child.__proto__ === parent; // true

parent.__proto__ === function.prototype; // true

function.prototype.__proto__ === object.prototype; // true

object.prototype.__proto__ === null; // true

// 2、例項原型鏈

child.__proto__ === child.prototype; // true

child.prototype.__proto__ === parent.prototype; // true

parent.prototype.__proto__ === object.prototype; // true

object.prototype.__proto__ === null; // true

複製**

es6 extends 繼承,主要就是

// es5 實現es6 extends的例子

function parent(name)

parent.sayhello = function

()parent.prototype.sayname = function

()function child(name, age)

// new

function

object

() f.prototype = proto;

return new f();

}function _inherits(child, parent)

_inherits(child, parent);

child.prototype.sayage = function

()var parent = new parent('parent');

var child = new child('child', 18);

複製**

上述兩中實現繼承的方式都是通過 [[prototype]] 機制來實現的,我們可以使用物件關聯的風格來實現上述功能

parent = ,

sayhello: function

(), sayname: function

() }

child = object.create( parent );

child.sayage = function

() var child1 = object.create( child );

child1.init( "tom" );

var child2 = object.create( child );

child2.init('lili');

child1.sayhello();

child2.sayname();

複製**

從上面**可以看出物件關聯風格的**顯然更加簡潔,因為這種**只關注一件事:物件之間的關聯關係, 使用類建構函式的話,你需要在同乙個步驟中實現構造和初始化。然而,在許多情況下把這兩步分開(就像物件關聯**一樣)更靈活。 物件關聯除了能讓**看起來更簡潔(並且更具擴充套件性)外還可以通過行為委託模式簡化**結構

ES6 類和繼承

class person 等價於 person.prototype.showname showname let p1 new person aaaa 12 表示式形式 const person class let p1 new person aaaa 12 變數定義方法名 let aaa ssss ...

es6 類的繼承

function animal name animal.prototype.drink function animal.prototype.eat function item function dog name,breed animal.prototype dog.prototype animal....

ES6 類的繼承

類的繼承 super 關鍵字 子類通過 extends 關鍵字來繼承父類的所有屬性和方法 子類必須在constructor中呼叫super方法,否則新建例項會報錯 es5的繼承中,實質是先創造子類的例項物件this,然後再將父類的方法 屬性新增到this上面。es6的繼承中,實質是先創造父類的例項物...