コンストラクターとクラスの役割:新しいキーワードを使用してオブジェクトを作成できます
2つの基本的な使用法の違い
アイテムを比較する | ES5(コンストラクターの記述方法) | ES6(クラスの書き方) |
---|---|---|
定義 | 関数Myobj(x){} | クラスMyobj {} |
コンストラクタ | 関数Myobj(){} | コンストラクタ(){} |
公共財産 | this.x = x | コンストラクター(x){this.x = x} |
パブリックメソッド | this.show = function(){} | コンストラクター(){this.show = function(){}} |
静的メソッド | Myobj.test = function(){} | 静的テスト= function(){} |
静的プロパティ | Myobj.staticProp = '静的プロパティ' | static staticProp = '静的プロパティ' |
プライベートメソッド | コンストラクター関数privateMethod(){}内でメソッドを定義します | プライベートメソッドをモジュール化する |
私有財産 | コンストラクター内で変数を定義しますletprivateProp = 'private property' | #privateProp = 'プライベートプロパティ' |
ES5継承メソッド(3種類)
プロトタイプ継承
function Base(name) {
this.name = name
this.show = function(){
console.log('show()')
}
}
function Sub(){
}
Sub.prototype = new Base()
適用バインド継承を呼び出す
//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エディターで使用するとエラーが報告されます(曲線を使用して国を保存します)