类别:媒体报道 发布时间:2021-01-11 浏览人次:
1. 借助构造函数实现继承
原理:改变子类运行时的 this 指向,但是父类原型链上的属性并没有被继承,是不完全的继承
function Parent() { this.name = 'Parent' Parent.prototype.say = function(){ console.log('hello') function Child() { Parent.call(this) this.type = 'Child' console.log(new Parent()) console.log(new Child())
2. 借助原型链实现继承
原理:原型链,但是在一个子类实例中改变了父类中的属性,其他实例中的该属性也会改变子,也是不完全的继承
function Parent() { this.name = 'Parent' this.arr = [1, 2, 3] Parent.prototype.say = function(){ console.log('hello') function Child() { this.type = 'Child' Child.prototype = new Parent() let s1 = new Child() let s2 = new Child() s1.arr.push(4) console.log(s1.arr, s2.arr) console.log(new Parent()) console.log(new Child()) console.log(new Child().say())
3. 构造函数 + 原型链
最佳实践
// 父类 function Parent() { this.name = 'Parent' this.arr = [1, 2, 3] Parent.prototype.say = function(){ console.log('hello') // 子类 function Child() { Parent.call(this) this.type = 'Child' // 避免父级的构造函数执行两次,共用一个 constructor // 但是无法区分实例属于哪个构造函数 // Child.prototype = Parent.prototype // 改进:创建一个中间对象,再修改子类的 constructor Child.prototype = Object.create(Parent.prototype) Child.prototype.constructor = Child // 实例化 let s1 = new Child() let s2 = new Child() let s3 = new Parent() 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(new Parent()) console.log(new Child()) console.log(new Child().say())
总结
以上所述是小编给大家介绍的JavaScript 面向对象(推荐)的相关知识,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
初探JavaScript 朝向目标(强烈推荐) 文章投稿:mrr js 朝向目标专业知识是最基本的新手入门专业知识点,下边根据文中案例编码给大伙儿详尽详细介绍js 朝向目标的专业知识,很感兴...
2021-01-11JavaScript正则表达式表述式和联级实际效果 正则表达式表述式(regular expression)是一种标识符串配对的方式,用于查验一字符串中是不是包括特定方式的标识符串。下边根据文中给...
2021-01-11APP服务平台开发设计、电子商务服务平台开发设计的总体处理计划方案服务广州市凡科APP开发设计企业出示超出5种流行开发设计服务,IOS开发设计、android开发设计,手机微信商城系统...
2021-01-11北京市企业网站建设企业的发展方向,是许多企业网站建设企业的头痛大事儿,北京市企业网站建设制造行业的公司老总们都会为公司找寻发展方向而争先创优奔波着,北京市企业网站...
2021-01-11js 原生态分辨內容地区是不是翻转究竟部的案例编码 下边小编就为大伙儿共享一篇js 原生态分辨內容地区是不是翻转究竟部的案例编码,具备非常好的参照使用价值,期待对大伙...
2021-01-11企业动态性制造行业新闻资讯建网站有关九度角度强烈推荐信息内容 在“互连网+”下被颠复的商业服务经济发展方式 重要词:互连网 共享资源经济发展 大生产制造 销售市场经济发展...
2021-01-11