You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// ES5寄生组合继承实现:// 父类被继承的对象functionsupFather(name){this.name=namethis.colors=['red','blue','green']// 复杂类型}supFather.prototype.sayName=function(age){console.log(this.name,'age')}// 子类functionSub(name,age){// 借用父类的方法:修改它的this指向,赋值父类的构造函数里面方法、属性到子类上supFather.call(this,name)this.age=age}// 重写子类的prototype,修正constructor指向functioninheritPrototype(sonFn,fatherFn){sonFn.prototype=Object.create(fatherFn.prototype)// 浅拷贝父类原型上的属性和方法sonFn.prototype.constructor=sonFn// 修正constructor指向到继承的那个函数上}//inheritPrototype(Sub,supFather)// 子类的prototype属性要写在后面 否则会被覆盖Sub.prototype.sayAge=function(){console.log(this.age,'foo')}// 实例化子类,可以在实例上找到属性、方法constinstance1=newSub('OBKoro1',24)constinstance2=newSub('小明',18)instance1.colors.push('black')console.log(instance1)// {"name":"OBKoro1","colors":["red","blue","green","black"],"age":24}console.log(instance2)// {"name":"小明","colors":["red","blue","green"],"age":18}// 使用ES5实现ES6 extends的例子// 其实就是上面ES5的寄生组合式继承的那个例子functionParent(name){this.name=name}Parent.sayHello=function(){console.log('hello')}Parent.prototype.sayName=function(){console.log(`my name is ${this.name}`)returnthis.name}functionChild(name,age){Parent.call(this,name)// 相当于调用superthis.age=age}// 继承原型function_inherits(Child,Parent){Child.prototype=Object.create(Parent.prototype)Child.prototype.constructor=ChildChild.__proto__=Parent}_inherits(Child,Parent)Child.prototype.sayAge=function(){console.log(`my age is ${this.age}`)returnthis.age}// 测试constparent=newParent('Parent')constchild=newChild('Child',18)console.log('parent: ',parent)// parent: Parent {name: "Parent"}Parent.sayHello()// helloparent.sayName()// my name is Parentconsole.log('child: ',child)// child: Child {name: "Child", age: 18}Child.sayHello()// hellochild.sayName()// my name is Childchild.sayAge()// my age is 18
The text was updated successfully, but these errors were encountered:
The text was updated successfully, but these errors were encountered: