js 继承
前段时间帮小学弟整理了一下 js 的继承
- JS有哪些手段可以实现继承?
- 对象冒充
- 在Child中创建临时变量this.flag 去接受 Parent 运行this.flag(参数) 实现继承 ---别忘了delete this.flag
- call()
- 在Child中 使用Parent.call(this, arguments[i], ...)
- apply()
- 在Child中 使用Parent.call(this, [arguments[i] , .....])
- 原型
- Child.prototype = new Parent()
- 混合式继承
- 原型继承和call() 结合
- 对象冒充
- 继承方式
- 都是以上继承手段的自由组合
- 我使用的构造函数的继承实现
function extend(A, B){ var Temp= function(){} Temp.prototype = B.prototype A.prototype = new Temp() A.prototype.constructor = A } function Parent (a){ this.name = a.name; this.sayHi = function(){ console.log(this.name) } } function Child (a){ Parent.call(this,a); this.age = a.age } extend(Child,Parent) var a = new Child({name:"tdk",age:19})
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步