一、构造函数基本的用法
构造函数的用于实例化对象,使其可以访问构造函数的私有信息的。
//实例化对象
const date = new Date()
const obj = new Object()
const form = new FormData()
const arr = new Array()
二、编写基本的构造函数
1.我们可以通过创建普通函数的方式来创建一个最简单的构造函数
function Counter(){
}
const f1 = new Counter()
//简单解释了(原型)继承关系,不理解没关系
console.log(Counter.__proto__ == Function.prototype) //true
console.log(f1.__proto__ == Counter.prototype) //true
console.log(f1.constructor == Counter) //true
2.添加一些属性和方法,来实现一个计数器
function Counter(){
this.num = 0
}
Counter.prototype.add = function(){
this.num++
}
Counter.prototype.minus = function(){
this.num--
}
const f1 = new Counter()
f1.add()
console.log(f1.num) //1
f1.add()
console.log(f1.num) //2
f1.minus()
console.log(f1.num) //1
3.继承Counter,实现一个自定义加减的计数器
function CounterPlus(){
Counter.call(this)
}
CounterPlus.prototype = Object.create(Counter.prototype)
CounterPlus.prototype.customAdd = function(number){
this.num+=number
}
const f2 = new CounterPlus()
f2.customAdd(100)
f2.add(1)
console.log(f2.num) //101
4.我们用ES6的class来重构下上面的构造函数
需要注意的是,class的继承和上方的原型继承有本质的区别,严格来说上方的继承方法并不是标准的继承方法。
一般情况下,js的所有数据的隐式原型都是其构造函数的显式原型,而继承父类的子类不同,他们的隐式原型是其所继承的父类(构造函数),而它的构造函数却是Funtion的显式原型。
强烈推荐使用ES6 class的方式来编写原型。
class Counter{
constructor(){
this.num = 0
}
add(){
this.num++
}
minus(){
this.num--
}
}
class CounterPlus extends Counter{
constructor(){
super()
}
customAdd(number){
this.num+=number
}
}
const f2 = new CounterPlus()
f2.customAdd(100)
f2.add()
console.log(f2.num) //101
延伸问题
什么是原型链
为什么js的所有数据的隐式原型都是其构造函数的显式原型,而继承父类的子类不同,他们的隐式原型是其所继承的父类(父构造函数),而它的构造函数却是Funtion的显式原型。
class进阶使用方法