初探JavaScript 面向对象(推荐)
类的声明
1.构造函数
functionAnimal(){
this.name='name'
}
//实例化
newAnimal()
2.ES6class
classAnimal{
constructor(){
this.name='name'
}
}
//实例化
newAnimal()
类的继承
1.借助构造函数实现继承
原理:改变子类运行时的this指向,但是父类原型链上的属性并没有被继承,是不完全的继承
functionParent(){
this.name='Parent'
}
Parent.prototype.say=function(){
console.log('hello')
}
functionChild(){
Parent.call(this)
this.type='Child'
}
console.log(newParent())
console.log(newChild())
2.借助原型链实现继承
原理:原型链,但是在一个子类实例中改变了父类中的属性,其他实例中的该属性也会改变子,也是不完全的继承
functionParent(){
this.name='Parent'
this.arr=[1,2,3]
}
Parent.prototype.say=function(){
console.log('hello')
}
functionChild(){
this.type='Child'
}
Child.prototype=newParent()
lets1=newChild()
lets2=newChild()
s1.arr.push(4)
console.log(s1.arr,s2.arr)
console.log(newParent())
console.log(newChild())
console.log(newChild().say())
3.构造函数+原型链
最佳实践
//父类
functionParent(){
this.name='Parent'
this.arr=[1,2,3]
}
Parent.prototype.say=function(){
console.log('hello')
}
//子类
functionChild(){
Parent.call(this)
this.type='Child'
}
//避免父级的构造函数执行两次,共用一个constructor
//但是无法区分实例属于哪个构造函数
//Child.prototype=Parent.prototype
//改进:创建一个中间对象,再修改子类的constructor
Child.prototype=Object.create(Parent.prototype)
Child.prototype.constructor=Child
//实例化
lets1=newChild()
lets2=newChild()
lets3=newParent()
s1.arr.push(4)
console.log(s1.arr,s2.arr)//[1,2,3,4][1,2,3]
console.log(s2.constructor)//Child
console.log(s3.constructor)//Parent
console.log(newParent())
console.log(newChild())
console.log(newChild().say())
总结
以上所述是小编给大家介绍的JavaScript面向对象(推荐)的相关知识,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下