当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 初探JavaScript 面向对象(推荐)

初探JavaScript 面向对象(推荐)

2017年12月12日  | 移动技术网IT编程  | 我要评论
类的声明 1. 构造函数 function animal() { this.name = 'name' } // 实例化 new animal()

类的声明

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 面向对象(推荐)的相关知识,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网