这次给大家带来js面向对象深入理解,js面向对象深入理解的注意事项有哪些,下面就是实战案例,一起来看一下。
类的声明
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())相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
乐尚商城系统是一项基于PHP+MYSQL为核心开发的一套免费 + 开源专业商城系统。软件具执行效率高、模板自由切换、后台管理功能方便等诸多优秀特点。 本软件是基于Web应用的B/S架构的商城网站建设解决方案的建站系统。它可以让用户高效、快速、低成本的构建个性化、专业化、强大功能的团购网站。从技术层面来看,本程序采用目前软件开发IT业界较为流行的PHP和MYSQL数据库开发技术,基于面向对象的编程
684
以上就是js面向对象深入理解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号