ES6之class类

使用ES6中的class创建对象
ES6引入了 Class(类)这个概念,作为创建对象的模板。创建对象的最佳方式就是组合使用构造函数和原型,其实,ES6 的class可以看作构造函数+原型创建对象的另一种写法,除了写法更符合面向对象编程的语法之外,并没有实质性的改变。
举个例子

js创建构造函数

//构造函数
function Fun(name, age) {
    this.name = name;
    this.age = age;
    //原型对象
    if (typeof(this.getName) != "function") {
        Fun.prototype.getName = function() {
            return this.name;
        }
    } 
}

//实例
var p1 = new Fun("Tom", 20);
//测试
console.log(p1.age);
console.log(p1.getName());
//输出:20,Tom

es6创建class类

//构造函数
class Fun {
    //原型对象上的方法
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    getName() {
        return this.name;
    }
}

//实例
var p1 = new Fun("Tom", 20);
//测试
console.log(p1.age);
console.log(p1.getName());
console.log(typeof(Fun));
//constructor属性指向其构造函数
console.log(p1.constructor == Fun);
//__proto__属性指向其原型
console.log(p1.__proto__ == Fun.prototype);
//输出:20,Tom,function,true,true

从上面的代码测试中可以看到:ES6中的class的数据类型是函数(构造函数也是函数),因此与函数一样,class也可以使用表达式的形式定义

//相同点
//类的数据类型就是函数,且指向构造函数;
//constructor中与构造函数中的this都是代表实例对象;
//实例上均可以使用new;
//类方法调用:类的所有方法都定义在其prototype上,故调用其实例上方法即调用其原型上的方法;
//实例的属性:除非显式定义在其本身(即定义在this对象上),否则都是定义在其原型上(即定义在class or proto上),即可以通过实例的proto属性为“类”添加方法
//原型对象:所有实例共享同一个;
//表达式:与函数一样,类也可以使用。
typeof Point // "function"
Point === Point.prototype.constructor // true
Point.prototype.constructor === Point // true

class Point {
//类必须定义constructor属性,如果没有显式定义,一个空的constructor方法会被默认添加。
//constructor方法默认返回实例对象this,但也可以指定返回另一个对象。
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
//类中定义方法时,前面不用加function,后面不得加,,方法全部都是定义在类的prototype属性中。
//类的内部定义的所有方法都是不可枚举的
//类和模块内部默认采取严格模式
  toString() {
    return `${this.x},${this.y}`;
  }
}
var point = new Point(2, 3);
point.toString() // (2, 3)
point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true

var p1 = new Point(2,3);
var p2 = new Point(3,2);
p1.__proto__ === p2.__proto__
//true
const MyClass = class Me {
	 constructor(x, y) {
	    this.x = x;
	    this.y = y;
	  }
};
//这个类的名字是MyClass而不是Me,Me只在 Class 的内部代码可用,可以省略,指代当前类。

//不同点:
//构造方法:class构造方法constructor,对应构造函数Point;
//constructor方法:类内部默认添加,生成实例时自动调用;
//类方法:类的内部所有定义的方法,都是不可枚举的,而ES5构造函数定义的可枚举;
//实例化:类必须使用new调用,否则会报错;
//类的属性名:可以采用表达式,,而ES5的不可以;
let methodName = 'back';
class Point {
  constructor(x, y) {
    // ...
  }
  toString() {
    // ...
  }
  [methodName]() {
    // ...
  }
}
let obj = new Point(1,2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值