constructor
function Fn(){this.x=10;}Fn.prototype.getX= function(){}let f =new Fn();Fn();class A{constructor(x){//类本身的函数this.x=x;//增加私有属性//return 的是基本数据类型对实例没有影响如果是引用数据类型会改变实例}}let a = new A(10);console.log(a.x);//10//A(); 报错,类必须使用new执行不可作为普通函数执行console.log(typeof A);//'function'
class 的name问题
let A = class AA{
//AA 只能在类里面使用 类的name都是AA
constructor(){
console.log(AA.name);
}
getA(){
console.log(AA.name);
}
}
let a =new A();
a.getA();
class执行问题
function BB(name){
this.name=name;
}
let bb =new BB('珠峰');
class AA{
constructor(name){
this.name=name;
}
}
let aa = new AA("培训");
console.log(aa);
//采用class表达式让类直接执行
let a1 = new class{
constructor(name){
console.log(name);
}
}('ES6');
class变量提升
//function 会有变量提升
FF();
new FF();
function FF(){
this.f="ff";
}
//ES6中的class跟let和const一样没有变量提升
new GG;//GGis not defined
class GG{
constructor(){
this.gg='gg';
}
}
class的静态方法
//类相当于原型,写在原型上的方法都被实例继承了,假如想给类本身加一些方法可以再方法前面加上一个关键字static,不会被实例继承,只有类本身可以使用
class AA{
constructor(){
this.a = "aa";
}
getA(){
console.log('1');
}
static getB(){
console.log('静态方法');
}
}
let aa =new AA;
aa.getA();
//aa.getB();//报错
AA.getB();
//静态方法可被子类继承
class F{
static getF(){
console.log('我是F的getF');
}
}
class G extends F{
constructor(){
super()
}
getF(){
super.getF();
}
}
G.getF();
原型上的方法不可枚举
function F(){
this.f = 'ff';
}
F.prototype.getF= function(){};
let f = new F;
for(let key in f){
console.log(key);
}
class FF{
constructor(){
this.ff="ff";
}
getF(){};
}
let ff = new FF;
for(let key in ff){
console.log(key);
}
继承
class A{
constructor(x){
this.x=x;
}
getX(){
console.log(this.x);
}
static getY(){
console.log(this);
}
}
A.getY();
//=>子类B继承父类A
class B extends A{
constructor(x){
//子类没有this this继承父类 super();//执行完成之后才会有this
//super()就是父类A的constructor;
//this.y=100;不可以在super执行之前使用this
super(x);
this.y=100;
}
getX(){
//=>super 指向父类原型
super.getX();
}
//=> 父类的静态/私有方法也可以继承
static getY(){
//super 父类本身
super.getY();
}
}
let b = new B('小郭');
b.getX();
B.getY();