构造函数和类的作用: 可以通过 new 关键字来创建一个对象
两者基本使用使用时的区别
比较项目 | ES5(构造函数写法) | ES6(类的写法) |
---|---|---|
定义 | function Myobj(x) {} | class Myobj{} |
构造函数 | function Myobj(){} | constructor(){} |
公共属性 | this.x = x | constructor(x){this.x=x} |
公共方法 | this.show = function(){} | constructor(){this.show=function(){}} |
静态方法 | Myobj.test = function(){} | static test = function(){} |
静态属性 | Myobj.staticProp=‘静态属性’ | static staticProp=‘静态属性’ |
私有方法 | 构造函数内部 定义一个方法 function privateMethod(){} | 将私有的方法模块化出去 |
私有属性 | 构造函数内部定义一个变量 let privateProp = ‘私有属性’ | #privateProp = ‘私有属性’ |
ES5的继承方法(三种)
原型继承
function Base(name) {
this.name = name
this.show = function(){
console.log('show()')
}
}
function Sub(){
}
Sub.prototype = new Base()
call apply bind继承
//call 继承
function Base(name) {
this.name = name
this.show = function(){
console.log('show()')
}
}
function Sub(name){
Base.call(this,name)
}
//或者apply继承
function Sub(name) {
Base.apply(this,[name])// 或者 Base.apply(this,arguments)
}
//或者bind继承
function Sub(name){
Base.bind(this,name)()
}
ES6的继承方式
class Base{
constructor(name) {//构造函数
this.name = name
this.show = function(){
console.log('show()')
}
}
}
class Sub extends Base{
constructor(name,color){
super(name)//继承父类的构造函数
this.color = color//子类新增的属性
this.addMethod = function(){
console.log('子类新增的方法')
}
}
}
ES5 各类属性方法应该如何定义书写
function Base(name){
this.publicProp = name//公有属性
this.publicMethod = function(){//公有方法
console.log('公有方法')
}
let privateProp = 10//私有属性
function privateMethod() {//私有方法
console.log('私有方法');
}
}
Base.staticProp = '静态属性'//静态属性
Base.staticMethod = function() {//静态方法
console.log('静态方法')
}
ES6各类属性方法应该如何定义书写
class Base {
static staticProp = '静态属性'
static staticMethod = function () {
console.log('静态方法', '')
}
constructor(name) {/* 构造函数 */
this.publicProp = name//公有属性
this.publicMethod = function () {//公有方法
console.log('公有方法')
}
}
callPrivate(args){
privateMethod.call(this,args)
}
}
function privateMethod(args){
console.log('私有方法')
}
#property 表示私有方法和属性现在只是提案, 我在vscode 编辑器中使用会报错(采用曲线救国的方法)