ES6 类(Class)基本用法和静态属性+方法详解

转载请注明预见才能遇见的博客:http://my.csdn.net/

原文地址:http://blog.csdn.net/pcaxb/article/details/53759637

ES6 类(Class)基本用法和静态属性+方法详解

JavaScript语言的传统方法是通过构造函数,定义并生成新对象,prototype 属性使您有能力向对象添加属性和方法。下面是通过传统的方式创建和使用对象的案例:

//Person.js
function Person(x,y){
    this.x = x;
    this.y = y;
}

Person.prototype.toString = function (){
    return (this.x + "的年龄是" +this.y+"岁");
}
export {Person};
//index.js
import {Person} from './Person';
let person = new Person('张三',12);
console.log(person.toString());

1.Class的基本用法

ES6引入了Class(类)这个概念,作为对象的模板,通过class关键字,可以定义类。基本上,ES6的class可以看作只是一个语法糖,它的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。上面的代码用ES6的“类”改写,就是下面这样。
//Person.js
class Person{
    // 构造
    constructor(x,y){
        this.x = x;
        this.y = y;
    }


    toString(){
        return (this.x + "的年龄是" +this.y+"岁");
    }
}
export {Person};
//index.js
import {Person} from './Person';
let person = new Person('张三',12);
console.log(person.toString());
上面代码定义了一个“类”,可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。也就是说,ES5的构造函数Person,对应ES6的Person类的构造方法。Person类除了构造方法,还定义了一个toString方法。注意,定义“类”的方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错。
ES6的类,完全可以看作构造函数的另一种写法。
//Person.js
console.log(typeof Person);//function
console.log(Person === Person.prototype.constructor);//true
上面代码表明,类的数据类型就是函数,类本身就指向构造函数。
//Person.js
console.log(Person.prototype);//输出的是一个对象
构造函数的prototype属性,在ES6的“类”上面继续存在。事实上,类的所有方法都定义在类的prototype属性上面,通过以下方式可是覆盖类中的方法,当然定义类的时候也可以通过这个方式添加方法。
//index.js
Person.prototype = {
    getName(){
        return '张三';
    },
    getAge(){
        return '12';
    }
};
在类的实例上面调用方法,其实就是调用原型上的方法
//index.js
console.log(person.constructor === Person.prototype.constructor);//true
Object.assign方法可以给对象Person动态的增加方法,而Person.prototype = {}是覆盖对象的方法,或者在初始化的时候添加方法。
//index.js
Object.assign(Person.prototype,{
    getWidth(){
        console.log('12');
    },
    getHeight(){
        console.log('24');
    }
});
console.log(Person.prototype);
toString方法是Person类内部定义的方法,ES6中它是不可枚举的,这一点与ES5的行为不一致,ES5是可以枚举的。

//index.js
//ES5
console.log(Object.keys(Person.prototype));//["toString", "getWidth", "getHeight"]
console.log(Object.getOwnPropertyNames(Person.prototype));//["constructor", "toString", "getWidth", "getHeight"]

//ES6
console.log(Object.keys(Person.prototype));//["getWidth", "getHeight"]
console.log(Object.getOwnPropertyNames(Person.prototype));//["constructor", "toString", "getWidth", "getHeight"]
Object.keys(obj),返回一个数组,数组里是该obj可被枚举的所有属性。Object.getOwnPropertyNames(obj),返回一个数组,数组里是该obj上所有的实例属性。

在ES6中,类的属性名可以使用表达式,具体实现方式如下

//Article.js
let methodName = "getTitle";
export default class Article{
    [methodName](){
        console.log('输出文章的标题1');
    }
}
//index.js
import Article from './Article';
//console.log(Article.prototype);
let article = new Article();
article.getTitle()
constructor方法是类的构造函数是默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个默认的constructor方法会被添加。所以即使你没有添加构造函数,也是有默认的构造函数的。一般constructor方法默认返回实例对象this,但是也可以指定constructor方法返回一个全新的对象,让返回的实例对象不是该类的实例。
//ConstructorStu.js
import Article from './Article';
export default class ConstructorStu{
    // 构造
    constructor() {
        console.log('constructor');
        return new Article();
    }
}
//index.js
import ConstructorStu from './ConstructorStu';
console.log('==111==');
console.log(new ConstructorStu() instanceof ConstructorStu);//false
console.log('==222==');
let cons =  new ConstructorStu();
console.log('==333==');
cons.constructor();
console.log('==444==');
运行结果
==111==
constructor
false
==222==
constructor
==333==
==444==
说明:类的构造函数,不使用new是没法调用的,即使你使用实例对象去调用也是不行的,这是它跟普通构造函数的一个主要区别。
实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。hasOwnProperty()函数用于指示一个对象自身(不包括原型链)是否具有指定名称的属性。如果有,返回true,否则返回false。
//Person.js
class Person{
    // 构造
    constructor(x,y){
        this.x = x;
        this.y = y;
    }

    toString(){
        return (this.x + "的年龄是" +this.y+"岁");
    }
}

let person = new Person('lis',8);
console.log(person.toString());
console.log(person.hasOwnProperty('x'));//true
console.log(person.hasOwnProperty('y'));//true
console.log(person.hasOwnProperty('toString'));//false
console.log(person.__proto__.hasOwnProperty('toString'));//true
说明:上面结果说明对象上有x,y属性,但是没有toString属性。也就是说x,y是定义在this对象上,toString定义在类上。
let person1 = new Person('张三',12);
let person2 = new Person('李四',13);
console.log(person1.__proto__ === person2.__proto__);//true
类的所有实例共享一个原型对象,person1和person2都是Person的实例,它们的原型都是Person.prototype,所以__proto__属性是相等的。这也意味着,可以通过实例的__proto__属性为Class添加方法。
let person1 = new Person('张三',12);
let person2 = new Person('李四',13);
person1.__proto__.getH = function (){
    return "Height";
};
console.log(person1.getH());
console.log(person2.getH());
上面代码在person1的原型上添加了一个getH方法,由于person1的原型就是person2的原型,因此person2也可以调用这个方法。而且,此后新建的实例person3也可以调用这个方法。这意味着,使用实例的__proto__属性改写原型,必须相当谨慎,不推荐使用,因为这会改变Class的原始定义,影响到所有实例。
__proto__参考资料:点击打开链接

class不存在变量提升,需要先定义再使用,因为ES6不会把类的声明提升到代码头部,但是ES5就不一样,ES5存在变量提升,可以先使用,然后再定义。
//正确
new A();
function A(){

}//ES5可以先使用再定义,存在变量提升
//错误
new B();
class B{

}//B is not a constructor
//ES6不能先使用再定义,不存在变量提升
这个类的名字是Expression而不是Expre,Expre只在Class的内部代码可用,指代当前类。
//Expression.js
const Expression = class Expre{

    static getAge(){
        return '12';
    }

    getClassName(){
        return " ClassName1= " +Expre.name + " ClassName2= " +Expression.name;
    }

};

let exp = new Expression();
//let exp = new Expre();错误
//bundle.js:7935 Uncaught ReferenceError: Expre is not defined
console.log(exp.getClassName());//ClassName1= Expre ClassName2= Expre
//console.log(Expre.getAge());错误
//bundle.js:7935 Uncaught ReferenceError: Expre is not defined
console.log(Expression.getAge());
说明:Expre.name和Expression.name返回的都是Expre,返回的都是当前。
如果类的内部没用到的话,可以省略Expre,也就是可以写成下面的形式
//Expression.js
const MyExpre = class{

   getClassName(){
        return MyExpre.name;
    }

};

let myExpre = new MyExpre();
console.log(myExpre.getClassName());//MyExpre
说明:如果省略了class后面的那个名字Expre,MyExpre.name返回的就是MyExpre,如果没有省略MyExpre.name返回就是class后面的那个名字Expre。
采用Class表达式,可以写出立即执行的Class
//Expression.js
let person = new class{

    // 构造
    constructor(props) {
        this.props = props;
    }

    getProps(){
        return this.props;
    }

}('构造函数的参数');

console.log(person.getProps());//构造函数的参数

私有方法是常见需求,但ES6不提供,只能通过变通方法模拟实现。一种做法是在命名上加以区别,在方法前面加上_(下划线),表示这是一个只限于内部使用的私有方法。但是,这种命名是不保险的,在类的外部,还是可以调用到这个方法。另一种方法就是索性将私有方法移出模块,因为模块内部的所有方法都是对外可见的。
//PrivateMethod.js
export default class PrivateMethod{

    // 构造
    constructor() {
    }

    getName(){
        priName();
    }
}

function priName(){
    console.log('私有方法测试');
}
//index.js
import PriMe from './PrivateMethod';
let prime = new PriMe();
prime.getName();
说明:通过这种方式还可以定义私有属性,同理。还有一种方法是利用Symbol值的唯一性,将私有方法的名字命名为一个Symbol值,不过这种方式稍微麻烦点。
类的方法内部如果含有this,它默认指向类的实例。getName方法中的this,默认指向ThisStu类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境,因为找不到name方法而导致报错。
//ThisStu.js
class ThisStu{

    getName(){
        return this.name();
    }

    name(){
        return '王五';
    }

}
export {ThisStu};

//index.js
import {ThisStu} from './ThisStu';
let thisStu = new ThisStu();
console.log(thisStu.getName());
const {getName} = thisStu;
getName();
//Cannot read property 'name' of undefined
一个比较简单的解决方法是,在构造方法中绑定this,这样就不会找不到name方法了。修改ThisStu.js文件如下:
//ThisStu.js
class ThisStu{
    // 构造
    constructor() {
        this.getName = this.getName.bind(this);
    }

    getName(){
        return this.name();
    }

    name(){
        return '王五';
    }

}
export {ThisStu};
使用构造函数,直接给当前实例的getName赋值,修改修改ThisStu.js文件的构造函数如下:
// 构造
constructor() {
    //this.getName = this.getName.bind(this);
    this.getName = ()=>{
        return this.name();
    }
}

2.Class的静态方法
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
//StaticMethod.js
//定义静态方法
static getAge(){
 return '获取Age的静态方法';
}
//通过类名直接调用
console.log(StaticMethod.getAge());
如果StaticMethod继承StaticMethodParent,StaticMethodParent的静态方法,可以被StaticMethod继承。
//StaticMethodParent.js
export default class StaticMethodParent{
    static getCommon(){
        return '父类的静态方法';
    }
}
//通过子类直接调用
console.log(StaticMethod.getCommon());
如果StaticMethod继承StaticMethodParent,StaticMethodParent的静态方法,可以在StaticMethod中用super调用。
//定义静态方法
static getAge(){
    //子类可以调用父类的静态方法
    console.log(super.getCommon());
    return '获取Age的静态方法';
}
说明:静态方法只能在静态方法中调用,不能再实例方法中调用。

3.Class静态属性和实例属性
静态属性指的是Class本身的属性,即Class.propname,而不是定义在实例对象(this)上的属性。ES6使用静态属性和实例属性:
//StaticMethod.js
//定义静态属性
StaticMethod.firstName = 'pca';
console.log(StaticMethod.firstName);
//定义实例属性
//ES6实例属性只能在constructor构造函数中定义
constructor() {
    super();
    this.width = '40cm';
}
getWidth(){
    return this.width;//使用的时候需要加上this
}
//为了可读性的目的,对于那些在constructor里面已经定义的实例属性,新写法允许直接列出。
width;
说明:目前ES6,只有这种写法可行,因为ES6明确规定,Class内部只有静态方法,没有静态属性。

ES7有一个静态属性的提案,目前Babel转码器支持。安装babel-preset-stage-0 包含了0-3的stage,可根据需要添加,不同的stage封装了不同的插件,官方推荐是使用stage-1
安装命令(根据自己的需求调整):
npm install --save babel-preset-stage-0
ES7使用静态属性和实例属性:
//StaticMethod.js
//ES7提案 定义静态属性
static lastName = 'pcaca';
//ES7定义实例属性
height = '150cm';
说明:ES7和ES6的静态属性和实例属性只是定义不一样,调用的方式是一样的

Class的静态方法/Class静态属性和实例属性的整个案例:
//StaticMethodParent.js
export default class StaticMethodParent{
    static getCommon(){
        return '父类的静态方法';
    }
}

//StaticMethod.js
import StaticMethodParent from './StaticMethodParent'

//定义静态属性和静态方法
class StaticMethod extends StaticMethodParent{
    //因为ES6明确规定,Class内部只有静态方法,没有静态属性,所以ES6在类中定义静态属性都是错误的。
    //static lastName = 'pcaca';ES6错误

    //ES7提案 定义静态属性
    //安装babel-preset-stage-0 包含了0-3的stage,可根据需要添加,
    //不同的stage封装了不同的插件,官方推荐是使用stage-1
    static lastName = 'pcaca';

    //ES7定义实例属性
    height = '150cm';

    getHeight(){
        return this.height;//ES7的使用也要加上this
    }

    //ES6实例属性只能在constructor构造函数中定义
    constructor() {
        super();
        this.width = '40cm';
    }

    //为了可读性的目的,对于那些在constructor里面已经定义的实例属性,新写法允许直接列出。
    width;

    getWidth(){
        return this.width;//使用的时候需要加上this
    }

    //定义静态方法
    static getAge(){
        //子类可以调用父类的静态方法
        console.log(super.getCommon());
        return '获取Age的静态方法';
    }
};

//定义静态属性
StaticMethod.firstName = 'pca';

export {StaticMethod};

//index.js
import {StaticMethod} from './StaticMethod';
console.log(StaticMethod.getAge());
console.log(StaticMethod.getCommon());
console.log(StaticMethod.firstName);
console.log(StaticMethod.lastName);
let staticMethod = new StaticMethod();
console.log(staticMethod.height);
console.log(staticMethod.getHeight());
console.log(staticMethod.width);
console.log(staticMethod.getWidth());
//staticMethod.getAge();//bundle.js:7906 Uncaught TypeError: staticMethod.getAge is not a function
参考资料:点击打开链接

ES6 类(Class)基本用法和静态属性+方法详解

博客地址:http://blog.csdn.net/pcaxb/article/details/53759637

下载地址:http://download.csdn.net/detail/pcaxb/9716137



  • 33
    点赞
  • 111
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
ES6中的class可以让我们更方便地定义和面向对象的编程模式。下面是一些关于ES6 class的详细解释: 1. 定义 使用class关键字定义一个名通常首字母大写。例如: ``` class Person { constructor(name, age) { this.name = name; this.age = age; } sayHello() { console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`); } } ``` 上面的代码定义了一个Person,包含一个构造函数和一个sayHello方法。 2. 构造函数 中的构造函数使用constructor关键字定义,用于初始化对象的属性。例如: ``` class Person { constructor(name, age) { this.name = name; this.age = age; } } ``` 上面的代码定义了一个Person,包含一个构造函数构造函数接收name和age两个参数,并将其分别赋值给对象的name和age属性。 3. 方法 中的方法可以像普通函数一样定义,例如: ``` class Person { constructor(name, age) { this.name = name; this.age = age; } sayHello() { console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`); } } ``` 上面的代码定义了一个Person,包含一个sayHello方法,该方法用于打印对象的name和age属性。 4. 继承 ES6中的class支持继承,使用extends关键字实现继承。例如: ``` class Student extends Person { constructor(name, age, grade) { super(name, age); this.grade = grade; } study() { console.log(`${this.name} is studying in grade ${this.grade}.`); } } ``` 上面的代码定义了一个Student,该继承自Person,包含一个构造函数和一个study方法构造函数接收name、age和grade三个参数,其中name和age由父构造函数初始化,grade由子构造函数初始化。 5. 静态方法 中的静态方法使用static关键字定义,可以直接通过名调用,例如: ``` class MathUtils { static add(x, y) { return x + y; } static subtract(x, y) { return x - y; } } ``` 上面的代码定义了一个MathUtils,包含两个静态方法add和subtract,这两个方法可以直接通过名调用。 6. 属性 ES6中的class支持定义属性,可以使用get和set关键字定义属性的读写方法。例如: ``` class Person { constructor(name, age) { this._name = name; this._age = age; } get name() { return this._name; } set name(name) { this._name = name; } get age() { return this._age; } set age(age) { this._age = age; } } ``` 上面的代码定义了一个Person,包含两个属性name和age,这两个属性的读写方法分别由get和set关键字定义。注意,属性名前面加上了一个下划线,这是一种约定俗成的做法,用于表示私有属性,防止属性被直接访问。 7. 静态属性 ES6中的class支持定义静态属性,使用static关键字定义静态属性。例如: ``` class MyClass { static myStaticProperty = 42; } ``` 上面的代码定义了一个MyClass,包含一个静态属性myStaticProperty,该属性的初始值为42。 总结: ES6中的class为JavaScript提供了更加完整和规范的面向对象编程模式,支持继承、静态方法属性等等。使用class可以让我们更方便地定义和对象,提高代码的可读性和维护性。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值