ES6 class(类)

更新日期: 2019-07-19阅读: 2.1k标签: class

概述

class (类)作为对象的模板被引入,可以通过 class 关键字定义类。类简要说明
类的本质是function,是基本原型继承的语法糖。所以,JS中继承的模型是不会被改变的。
类既然是函数,那与函数有何不同呢?我们为什么要使用类呢?
有时间,先看一下MDN od

  • 函数声明可以被提升,而类声明与let/const 声明类似,不能被提升,也就是在真正执行声明之前,它们会一直存在于临时死区中。
  • 类声明中的所有代码将自动运行在严格模式下,而且无法强行让代码脱离严格模式。
  • 类中的所有方法,都是不可枚举的。而普通自定义类型中,必须通过Object.defineProperty()方法来指定某方法不可枚举。
  • 每个类都有一个[[Construct]]的内部方法,通过关键字new调用那些不含[[Construct]]的方法会导致程序抛出错误。
  • 使用除关键字new之外的方式调用构造函数会导致程序抛出错误。
  • 在类中修改类名会导致程序报错。


类声明

首先class关键字,然后是类的名字,其它部分的语法,类似于对象字面量方法的简写形式,但不需要在各元素之间使用逗号分隔。

class HelloClass {
    constructor(greeting) {
        this.greeting = greeting;
    }
    
    sayGreeting(){
        console.log(this.greeting);
    }
}

let hello = new HelloClass('Hello');
hello.sayGreeting();  // Hello

console.log(hello instanceof HelloClass);  // true
console.log(hello instanceof Object);  // true

console.log(typeof HelloClass);  // function
console.log(typeof HelloClass.prototype.sayGreeting); // function

分析:

  1. constructor为保留方法名,是用来构建对象的,不可用作其它用途。
  2. 函数定义之前,不需要添加function关键字。
  3. 类的属性不可被赋予新值,HelloClass.prototype是一个只可读类属性。

与之等价的ES5声明

let HelloClass = (function(){
    "use strict";
    const HelloClass  = function(greeting) {
        if (typeof new.target === 'undefined') {
            throw new Error("必须通过关键字new调用构造函数");
        }
        this.greeting = greeting;

        Object.defineProperty(HelloClass.prototype, "sayGreeting", {
            value: function() {
                if (typeof new.target !== 'undefined') {
                    throw new Error("不可使用关键字new调用构造函数");
                }
                console.log(this.greeting);
            },
            enumerable: false,
            writable: true,
            configurable: true
        });        
    }
    return HelloClass;
}());

let hello = new HelloClass('Hello');
hello.sayGreeting();

console.log(hello instanceof HelloClass);
console.log(hello instanceof Object);

console.log(typeof HelloClass);
console.log(typeof HelloClass.prototype.sayGreeting);


类表达式

类表达式可以是被命名的或匿名的。赋予一个命名类表达式的名称是类的主体的本地名称。和function的表达式类似,但不会像函数声名或和函数表达式一样被提升。

/* 匿名类 */ 
let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(typeof Rectangle); // function
/* 命名的类 */ 
let Rectangle = class Rectangle1 {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(typeof Rectange); // function
console.log(typeof Rectange1); // undefined

在JS中,函数为一等“公民”,可以传入函数,也可以从函数中返回,还可以赋值给变量的值。也是JS中的一等公民。


访问器

- getter
- setter
class Rectangle {
    // constructor
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
    // Getter
    get area() {
        return this.calcArea()
    }
    // Method
    calcArea() {
        return this.height * this.width;
    }
}
const square = new Rectangle(10, 10);

console.log(square.area);
// 100


可计算成员

const methodName = "sayGreeting";
class HelloClass {
    constructor(greeting) {
        this.greeting = greeting;
    }
    
    [methodName]() {
        console.log(this.greeting);
    }
}

let hello = new HelloClass('Hello');
hello.sayGreeting(); // Hello
hello[methodName](); // Hello

可计算访问器属性。

const propertyName = "greeting";
class HelloClass {
    constructor() {
        
    }
    
    get [propertyName]() {
        return this.greetingStr;
    }
    set [propertyName](value) {
        this.greetingStr = value;
    }
}

let hello = new HelloClass();
hello.greeting = 'Hello';
console.log(hello.greeting);


生成器方法

class NormClass {
    *createIterator() {
        yield 1;
        yield 2;
        yield 3;
    }
}
let instance = new NormClass();
let iterator = instance.createIterator();
console.log(iterator.next());  // { value: 1, done: false }
console.log(iterator.next());  // { value: 2, done: false }
console.log(iterator.next());  // { value: 3, done: false }
console.log(iterator.next());  // { value: undefined, done: true }

为类定义默认迭代器。

class Collection {
    constructor() {
        this.items = [];
    }

    *[Symbol.iterator]() {
        yield *this.items.values();
    }
}

var coll = new Collection();
coll.items.push(1);
coll.items.push(2);
coll.items.push(3);
for (let i of coll) {
    console.log(i);
}
// 1
// 2
// 3


静态成员

class Animal { 
    speak() {
      return this;
    }
    static eat() {
      return this;
    }
  }
  
  let obj = new Animal();
  console.log(obj.speak()); // Animal {}
  let speak = obj.speak;
  console.log(speak()); // undefined
  
  console.log(Animal.eat()); // class Animal
  let eat = Animal.eat;
  console.log(eat()); // undefined

链接: https://www.fly63.com/article/detial/4250

ES6 class创建对象和传统方法生成对象的区别

JS语言传统创建对象的方法一般是通过构造函数,来定义生成的,下面是一个使用function生成的例子。ES5是先新建子类的实例对象this,再将父类的属性添加到子类上,由于父类的内部属性无法获取,导致无法继承原生的构造函数

es6新特性之 class 基本用法

ES6 提供了更接近传统语言的写法,引入了 class(类)这个概念,作为对象的模板。通过class关键字,可以定义类

mixin配合class实现多继承的绝佳妙用

mixin一般翻译为“混入”、“混合”, 早期一般解释为:把一个对象的方法和属性拷贝到另一个对象上;Mixin是一种思想,用来实现代码高度可复用性,又可以用来解决多继承的问题,是一种非常灵活的设计模式

Class:向传统类模式转变的构造函数

JS基于原型的类,一直被转行前端的码僚们大呼惊奇,但接近传统模式使用class关键字定义的出现,ES6的class只是个语法糖,其定义生成的对象依然构造函数。不过为了与构造函数模式区分开,我们称其为类模式。

JS 总结之class

class 是 ES6 的新特性,可以用来定义一个类,实际上,class 只是一种语法糖,它是构造函数的另一种写法。用法和使用构造函数一样,通过 new 来生成对象实例

class 类 this指向的问题

ES6中的 class定义一个类, 其内部包含 constructor构造函数, 除了在构造函数显示的定义一些属性, 其余的默认都添加到这个类的原型对象上。以上代码 classProxy(prosen2) 返回的是包含一层拦截器的实例对象, 当读取 sayName这个函数的是和会出发 get拦截等操作。

classList介绍和原生JavaScript实现addClass、removeClass等

使用jQuery可以给元素很方便的添加class和删除class等操作,现在原生的JavaScript也可以实现这个方法了。使用classList可以方便的添加class、删除class、查询class等。elementClasses 是一个 DOMTokenList 表示 element 的类属性 。

Class 的私有属性与私有方法

proposal-class-fields与proposal-private-methods定义了 Class 的私有属性以及私有方法,这 2 个提案已经处于 Stage 3,这就意味着它们已经基本确定下来了,等待被加入到新的 ECMAScript 版本中。

ES6 static

ES6中新增了class这个语法糖。此class并非java中的class,ES6中的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。其中有static关键字。

vue.js 动态绑定class

vue 指令以 v- 前缀标示,数据绑定的指令 v-bind:属性名, 简写为 :属性名, 简单的数据绑定例子如下;vue 的分隔符默认是 {{ }}, 在分隔符里面的字符串会被认为是数据变量,可以通过 方式设置class

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!