1 , 类的申明
let obj = function(){
this.name = 'heh' ;
}
<!--es6中类的申明-->
class obj = {
constructor () {
this.name = 'heh';
}
getName(){
return this.name;
}
}
2 , 类的继承
<!--es6中类的继承-->
class parent {
constructor(name,age){
this.name = name ;
this.age = age ;
}
getName(){
console.log(this.name)
}
}
class child extends parent {
constructor(name,age){
<!--此处是核心-->
supper(name,age,color) ;
this.color = color
}
getColor(){
console.log(this.color) ;
}
}
let _parent = new parent('beiyue',24) ;
let _child = new child('nanan') ;
_parent.getName() ;
<!--beiyue-->
_child.getName() ;
<!--nanan-->
<!--非es6的继承-->
<!--父级-->
function parent(name,age){
this.name = name ;
this.age = age ;
this.getName = function(){
console.log(this.name) ;
}
}
parent.prototype.getAge = function(){
console.log(this.age) ;
}
<!--原型链的继承-->
function child(){
}
child.prototype = new parent(name,age) ;
child.prototype.toLog = function(){
console.log(1) ;
}
let obj2 = new child() ;
<!--
缺点:
child.prototype = {
toTo(){
console.log(1) ;
}
}
会断开与parent的联系
let obj2 = new child() 不能传入参数
-->
<!--借用构造函数-->
function child(){
parent.call(this,'an',23) ;
}
<!--
缺点:函数不能复用 , 不能继承方法
-->
<!--组合继承-->
function child(name,age){
<!--继承属性-->
parent.call(this,name,age) ; --- 第二次调用
this.color = ['red','orange'] ;
}
<!--继承方法-->
child.prototype = new parent() ; --- 第一次调用
child.prototype.constructor = child ;
let obj = new child(name,age) ;
<!--
缺点:无论什么情况都会调用2次超类型构造函数
-->
<!--原型式继承-->
function object(o){
function F(){} ;
F.prototype = o ;
return new F() ;
}
let obj1 = {
name:'beiyue',
getName:function(){
return this.name ;
}
} ;
let child1 = object(obj1) ;
-----------------------------------
let child1 = Object.create(obj1,{
name:{
value:'an' ;
}
})
<!--寄生式继承-->
function createChild(obj){
<!--创建新对象-->
let clone = object(obj) ;
<!--增加方法-->
clone.sayHi = function(){
alert('hahhaha')
}
<!--返回这个对象-->
return clone ;
}
<!--组合继承式继承-->
function inhritPrototype(obj1,obj2){
<!--创建对象-->
let prototype = object(obj2.prototype) ;
<!--增强对象-->
prototype.constructor = obj1 ;
<!--指定对象-->
obj1.prototype = prototype ;
}
function parent(name,age) {
this.name = name ;
this.age = age ;
}
parent.prototype.getName = function(){
return this.name ;
}
function child(name,age){
<!--注意此处-->
parent.call(this,name,age) ;
}
setPrototype(child,parent) ;
let childs = new child('an',24) ;
console.log(childs.getName());
关于js中的继承
最新推荐文章于 2023-07-14 20:40:49 发布