夜下客

繁体版 简体版
夜下客 > JS修炼法则 > 第9章 继承

第9章 继承

a wa wa');

class Cat extends Animal {

constructor(name, age) {

super(name)

this.age = age

const panda = new Cat('熊猫盼盼', 2);

panda.say()

8. 扩展:JS 模拟 class

8-1. 构造函数法

function Animal(name) {

this.name = name

Animal.prototype.say = function () {

console.log('wa wa')

let cat = new Animal('cat')

优点:思路简单 缺点:复杂,使用 this 和 prottype,可读性差

8-2. Object.create()法

var Animal = {

name: '只能写死',

say: function () {

console.log('wa wa')

},

let cat = Object.create(Animal)

优点:简单 缺点:实例不能实现私有属性和私有方法, 实例不能共享属性。

8-3. 极简主义法

var Animal = {

// Object.create()

createNew: function () {

let cat = {}

let privateName = 'AJ'

cat.name = '只能写死'

cat.say = function () {

console.log(privateName)

console.log('wa wa')

return cat

},

let cat = Animal.createNew()

console.log(cat.privateName) // undefined, 无法访问, 只能通过say()

如果希望 Cat 继承 Animal,只需要在 Cat.createNew() 中调用 Animal.createNew()。 如果希望 实例 有私有属性和方法,则通过在 createNew() 中 声明变量即可。 如果希望 实例 共享属性和方法,则通过在 createNew() 外部 声明变量即可。

8-4. Babel 在线转换

Babel在线转换

ES6 语法:

class Animal {

constructor(name, age) {

this.name = name

this.age = age

say() {

console.log('wa wa wa')

ES5 语法:

'use strict'

function _instanceof(left, right) {

if (

right != null &&

typeof Symbol !== 'undefined' &&

right[Symbol.hasInstance]

) {

return !!right[Symbol.hasInstance](left)

} else {

return left instanceof right

function _classCallCheck(instance, Constructor) {

if (!_instanceof(instance, Constructor

『加入书签,方便阅读』