ES 6新規構文(3)——対象
2794 ワード
ES 6におけるjsonの2つの変化
let a=12,b=5;
let json = {
a,
b
}
console.log(json) // { a:12 , b:5 }
let persen ={
name:' ',
age:18,
showName(){
alert(this.name)
}
}
persen.showName()
ES 6と従来のオブジェクト向け
従来のオブジェクト向け:クラスとコンストラクション関数を組み合わせて、オブジェクトにメソッドを追加するときにprototypeを使用します.従来のオブジェクト指向の例は次のとおりです.
function Person(name,age){
this.name = name;
this.age = age
}
Person.prototype.showName = function(){
console.log(' ',this.name)
}
Person.prototype.showAge = function(){
console.log(' ',this.age,' ')
}
var p = new Person(' ',18)
p.showName()
p.showAge()
ES 6オブジェクト向け:クラスとコンストラクション関数を分離します.
クラス:class
コンストラクション関数:constructorとは、インスタンスを生成した後、自分で実行する関数です.
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
//
showName(){
console.log(' ',this.name)
}
showAge(){
console.log(' ',this.age," ")
}
}
var p =new Person(' ',18);
p.showName();
p.showAge()
オブジェクトへの継承
従来のオブジェクト向け継承:
applyメソッドを使用して、子クラスは親クラスのすべての属性を継承します.
prototypeメソッドを使用して、子クラスが親クラスを継承するメソッド.
従来のオブジェクト向け継承の例は次のとおりです.
function Person(name,age){
this.name = name;
this.age = age
}
Person.prototype.showName = function(){
console.log(' ',this.name)
}
Person.prototype.showAge = function(){
console.log(' ',this.age,' ')
}
function Worker(name,age,job){
Person.apply(this,arguments)//
this.job = job
}
Worker.prototype = new Person();//
Worker.prototype.showJob = function(){
console.log(' ',this.job);
}
var w = new Worker(' ',18,' ');
w.showName();
w.showAge();
w.showJob();
ES 6オブジェクト継承向け:
extendsを使用して子クラスの親への継承を実現し、super()は親クラスの属性を継承します.
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
showName(){
console.log(' ',this.name)
}
showAge(){
console.log(' ',this.age," ")
}
}
class Worker extends Person {
constructor(name,age,job){
super(name,age)
this.job = job
}
showJob(){
console.log(' ',this.job)
}
}
var w = new Worker(' ',18,' ');
w.showName();
w.showAge();
w.showJob()
superについて:
サブクラスにはconstructorがあり、内部にsuperが必要です.サブクラスには独自のthisオブジェクトがないため、親クラスのthisオブジェクトを継承する必要があります.
ここでsuper(name,age)は親を呼び出す構造関数である.
superはPersonのコンストラクション関数を表すが,サブクラスWorkerのインスタンスを返す.
ES 6オブジェクト向けの利点
ES 6オブジェクト向けは従来のオブジェクト向けよりも文法が簡略化されている
ES 6文法標準、統一、大プロジェクト開発に適しており、衝突しにくい.
ES 6はシステムが提供する標準的な構文であり、互換性の問題を無視することができる.