一.ES5构造函数与继承
小问题: new关键字做了什么?
new会创建对象,将构造函数中的this指向创建出来的对象,也就是这个实例
方法一.利用apply或call方法
代码演示
function User(username,password){
this.username = username
this.password = password
this.login = function(){
console.log('登录')
}
}
function Admin(username,password){
User.apply(this,arguments)
this.delete = funciton(){
console.log('删除')
}
}
let Manage = new Admin('zhanghao','mima')
console.log(Manage) //Admin {
username: 'zhanghao',
password: 'mima',
login: [Function (anonymous)],
delete: [Function (anonymous)]
}
方法二.利用prototype
代码演示
function User(username,password){
this.username = username
this.password = password
this.login = function(){
console.log('登录')
}
}
function Admin(username,password){
this.delete = funciton(){
console.log('删除')
}
}
Admin.prototype = new User() //将User实例赋值给Admin.prototype,那么Admin的实例也就可以追溯上去从而使用User的东西完成函 数的方法继承效果
let Manage = new Admin('zhanghao','mima')
console.log(Manage.username) //undefined
Manage.login() //登录
Manage.delete() //删除
二. ES6类与继承
代码演示
// 生成类
class User {
constructor(username,password){
this.username = username
this.password = password
}
login(){
console.log(this)
console.log('登录')
}
}
// 继承类,并且再多添加点东西
class Admin extends User {
delete(){
console.log('删除')
}
}
let Manage = new Admin('zhanghao','mima')
Manage.login() //Admin { username: 'zhanghao', password: 'mima' }
登录
Manage.delete() //删除
tips:
(1).一般情况constructor中不要用return,不然会导致类下面的函数不会被暴露给实例使用