这是我参与8月更文挑战的第18天,活动详情查看:8月更文挑战
继承的实现
通过原型链实现继承
优点:可以访问父类的属性和方法和原型上的属性和方法
缺点:继承如果是引用类型,其中一个子类进行修改,全部都会受到影响,造成实例共享 如下:
function Parent(){
this.arr = [ 1, 2 ]
}
function Child(){
this.name = ['kebi']
}
Child.prototype = new Parent()
var person1 = new Child()
person1.arr.push('kuli')
console.log(person1.arr) //[1,2,'kebi','kuli']
var person2 = new Child()
console.log(person2.arr) // [1,2,'kebi',kuli]
*/
function Praent(){
this.lastName = 'wang'
}
Parent.prototype.asset = ['house','car']
function Child(){
}
Child.prototype = new Parent()
var child = new Child()
var child1 = new Child()
child.asset.push('plane')
console.log(child.lastName) // 'wang'
console.log(child1.asset) //['house','car',plane]
复制代码
通过call来继承
优点:可以保证每个子类维护自己的属性
缺点:无妨访问原型链上的属性和方法
function Parent(){
this.lastName = 'wang'
this.hobby = ['a','b']
}
Parent.prototype.asset = ['house','car']
function Child(){
Parent.call(this)
}
var child = new Child()
var child1 = new Child()
child.hobby.push('c')
console.log(child.lastName) // 'wang'
console.log(child1.hobby) // ['a','b']
console.log(child1.asset) //undefined
复制代码
组合继承 将两个结合
优点:既可以访问原型上的属性和方法,又可以每个子类维护自己属性
缺点:每次创建一个子类实例,父类都会被执行一次
function Parent(){
this.lastName = 'wang'
this.hobby = ['a','b']
}
Parent.prototype.asset = ['house','car']
function Child(){
Parent.call(this)
}
Child.prototype = new Parent()
var child = new Child()
var child1 = new Child()
child.hobby.push('c')
console.log(child.lastName) // 'wang'
console.log(child.hobby) // ['a','b','c']
复制代码
new操作符都做了些什么
1.创建一个空的对象
2.将空对象的proto属性指向构造函数的原型
3.将this的指向这个原型
4.返回这个对象
手写promise
promise 对象代表了未来将要发生的事件,用来传递异步操作信息。解决了回调地狱的问题
promise 对象有两个特点:
1.对象的状态不收外界影响。promise对象代表一个异步操作,有三种状态
1.pending:初始状态
2.fulfilled:操作完成
3.rejected:操作失败
2.一旦状态改变,就不会再变,任何时候都可以得到这个结果。promise对象的状态改变只有两种可能:从pending 变为 resolved 和 pengding 变为 rejected。
promise的优缺点
优点:可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调地狱。
缺点:无法取消promise,一旦新建他就会立即执行,无法取消。其次,如果不设置回调函数,promise内部抛出错误,不会反应到外部。第三,当处于pending状态时,无法得知目前进展到哪一阶段
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END