The role of the constructor and class: You can create an object through the new keyword
The difference between the two basic use
Compare items | ES5 (writing method of constructor) | ES6 (How to write a class) |
---|---|---|
definition | function Myobj(x) {} | class Myobj{} |
Constructor | function Myobj(){} | constructor(){} |
Public property | this.x = x | constructor(x){this.x=x} |
Public method | this.show = function(){} | constructor(){this.show=function(){}} |
Static method | Myobj.test = function(){} | static test = function(){} |
Static properties | Myobj.staticProp='Static property' | static staticProp='Static property' |
Private method | Define a method inside the constructor function privateMethod(){} | Modularize private methods |
Private property | Define a variable inside the constructor let privateProp ='private property' | #privateProp ='Private Properties' |
ES5 inheritance methods (three types)
prototype inheritance
function Base(name) {
this.name = name
this.show = function(){
console.log('show()')
}
}
function Sub(){
}
Sub.prototype = new Base()
call apply bind inheritance
//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 inheritance
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('子类新增的方法')
}
}
}
How to define and write ES5 various attribute methods
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('静态方法')
}
How to define and write ES6 various attribute methods
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 means that private methods and properties are only proposals now, I will report an error when I use it in the vscode editor (using the curve to save the country)