类的声明
1. 构造函数
function Animal() { this.name = 'name' } // 实例化 new Animal()
2. ES6 class
class Animal { constructor() { this.name = 'name' } } // 实例化 new Animal()
类的继承
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 面向对象(推荐)的相关知识,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
标签:
js,面向对象
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com
暂无“初探JavaScript 面向对象(推荐)”评论...
稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!
昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。
这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。
而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?