JS构造函数与类

57 阅读1分钟

如何自制一个构造函数

它可创建一个含有nameage的对象,并且所有Person构造出来的对象(Person对象)都能sayHi、run

Person既是函数,又是一个特殊的对象

function Person(name = '匿名', age = 0) {
    const obj = Object.create(Person.共有属性);
    //相当于 obj.隐藏属性 = Person.共有属性
    //Person对象自有属性
    obj.name = name
    ovj.age = age
    return obj
}

Person.共有属性 = {
    //Person对象共有属性
    constructor: Person,
    sayHi() {
        console.log(`我是${this.name}`)
    },
    run() {
        console.log(`${this.name}在跑步`)
    }
}

const f = Person('tao', 18)
f.sayHi()
f.run()

但是,上面的代码不够简洁,JS之父有话说,看一看下面的代码

第一种写法

function Person(name = '匿名', age = 0) {
    //Person对象自有属性
    obj.name = name
    obj.age = age
}

Person.prototype = {
    //Person对象共有属性
    constructor: Person,
    sayHi() {
        console.log(`我是${this.name}`)
    },
    run() {
        console.log(`${this.name}在跑步`)
    }
}

const f = new Person('tao', 18)
f.sayHi()
f.run()

省去两行代码,加了一个new, 用new的好处

  1. new 帮你创建一个新对象
  2. new 帮你准备Person.共有属性
  3. new 帮你关联隐藏属性与共有属性
  4. new 帮你return对象

因为Java程序员的原因,我要class!!!

第二种写法

class Person{
    //static x = 1
    constructor(name = '匿名', age = 0) {
        //Person对象自有属性
        obj.name = name
        obj.age = age
    }
    
    //Person对象共有属性
    sayHi() {
        console.log(`我是${this.name}`)
    },
    run() {
        console.log(`${this.name}在跑步`)
    }
}

const f = new Person('tao', 18)
f.sayHi()
f.run()
//console.log(Person.x) //1

缺陷(影响不大):

  1. 共有一个非函数属性, class写法做不到
  2. 直接给Person函数添加一个属性, class写法不推荐,推荐用static,见上面代码

注意: 箭头函数不能做构造函数,因为它不支持this(即箭头函数里面的this.x === window.x , 没有意义),不自带prototype