发布于 2017-09-09 22:56:05 | 110 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Javascript教程,程序狗速度看过来!

JavaScript客户端脚本语言

Javascript 是一种由Netscape的LiveScript发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如Perl,遗留的速度问题,为客户提供更流畅的浏览效果。


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())

总结

以上所述是小编给大家介绍的JavaScript 面向对象(推荐)的相关知识,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务