3

构造类以及继承

构造函数方法

function Person(name) {
    this.name = name
}

Person.prototype.species = 'human'
Person.prototype.sayName = {
    alert(this.name)
}

let person = new Person()

person.sayName()
  • 该种方式下的继承

(1)封装一个函数

function extend (child, Parent) {
    let F = function(){}
    F.prototype = Parent.prototype
    child.prototype = new F()
    child.prototype.constructor = child
}
function Man (name) {this.name = name}
extend(Man, Person)
let man1 = new Man('ziv')
console.log(man1.species) // human

(2)绑定

function Man () {
    Person.call(this, arguments) // call,apply,bind
}

(3)复制继承

function Man () {}
for (let prop in Person.prototype) {
    // 
    Man.prototype[prop] = Person.prototype[prop]
}

Man.prototype.constructor = Man

对象创建方法

let Person = {
    name: 'michal',
    sayName: function() {
        alert(this.name)
    }
}

let person = Object.create(Person)
person.sayName()

class类的实现

class Point {
    constructor(x, y) {
        this.x = x
        this.y = y
    }
    toString() {
        return `( ${this.x} ,${this.y} )`
    }
}
  • 该种方式下的继承
class micPoint extends Point(x, y, z) {
    constructor() {
        super(x, y)
        this.z = z    
    }
    toString () {
        return this.z + '' + super.toString()
    }
    
}

let point = new Point(2, 3)

极简主义法

  • 实现一个类
let Animal = {
    createNew: function() {
        let animal = {}
        animal.name = 'animal'
        animal.sleep = function() {console.log('睡觉')}
        return animal
    }
}
let animal1 = Animal.createNew()
animal1.sleep() // 睡觉
  • 类的私有属性和方法
let Cat = {
    createNew: function() {
        let cat = {}
        // 在createNew()方法中,只要不是定义在cat对象上的方法和属性,都是私有的
        let sound = 'miaomiao' // 该sound变量只能通过公有方法makeSound()来读取
        cat.makeSound = function (){console.log(sound)}
        return cat
    }
}
let cat2 = Cat.createNew()
console.log(cat2.sound) // undefined
  • 类的数据共享
let Cat = {
    sound: '喵喵'
    createNew: function(){
        let cat = {}
        cat.makeSound = function(){console.log(Cat.sound)}
        cat.changeSound = function(x){Cat.sound = x}
        return cat
    }
}
let cat1 = Cat.createNew()
let cat2 = Cat.createNew()
cat1.makeSound() // 喵喵
cat2.changeSound('汪汪') // 修改了共享的数据,另一个实例对象也会受到影响
cat1.makeSound() // 汪汪 
  • 该种方式下的继承实现
let Cat = {
    createNew: function() {
        let cat = Animal.createNew()
        cat.name = 'miao'
       
        cat.makeSound = function () {console.log('喵喵')}
        return cat
    }
}

let cat1 = Cat.createNew() // 该实例会继承Cat和Animal类
cat1.sleep() // 睡觉

luckyziv
1.2k 声望52 粉丝

摸索中前进!!


« 上一篇
学习Promise
下一篇 »
ES6的Class学习