标签: es6-class

具有静态箭头功能的类

我目前正在实施静态土地规范(幻想土地的另一种选择).我不仅要使用普通对象作为类型,还要使用静态方法的ES2015类.我已经将这些静态方法实现为curry形式的箭头函数而不是普通函数.但是,ES2015类无法实现这一点:

class List extends Array {
  static map = f => xs => xs.map(x => f(x))
  static of = x => [x]
}
Run Code Online (Sandbox Code Playgroud)

map不需要它自己this,因为它只是List构造函数的curry函数.为了使它工作,我必须写static map(f) { return xs => xs.map(x => f(x)) },什么是非常烦人的.

  • 为什么我不能在ES2015类中使用箭头函数和赋值表达式?
  • 有没有简洁的方法来实现我的目标?

javascript functional-programming ecmascript-6 arrow-functions es6-class

10
推荐指数
1
解决办法
3483
查看次数

伊斯坦布尔分公司覆盖率为ES6级应为100%但仅为75%

我写了一个非常简单的类和一些单元测试.覆盖率报告应该是100%,但我看到75%的分支机构.

在此输入图像描述

我无法弄清楚如何达到100%,我应该在哪里寻找我所缺少的东西.

UPDATE

单元测试:

/* global describe jest it expect */

import GenericDice from '../generic-dice-vanilla';

jest.unmock('../generic-dice-vanilla');

describe('GenericDice', () => {
  it('exists.', () => {
    expect(GenericDice).toBeDefined();
  });

  it('has a default face property set to 1', () => {
    const dice = new GenericDice();

    expect(dice.face).toBe(1);
  });

  it('has a default rolling property set to true', () => {
    const dice = new GenericDice();

    expect(dice.rolling).toBe(true);
  });

  it('has a default animation property set to an empty string', () => {
    const dice = new GenericDice(); …
Run Code Online (Sandbox Code Playgroud)

istanbul es6-class

10
推荐指数
1
解决办法
1897
查看次数

无法在Node.js中的ES6中定义的类中调用方法

我正在使用Node.js,Express.js和MongoDB制作应用程序.我正在使用MVC模式,并且还有单独的路由文件.我正在尝试创建一个Controller类,其中一个方法调用在其中声明的另一个方法.但我似乎无法做到这一点.我得到"无法读取未定义的属性".

index.js文件

let express = require('express');
let app = express();

let productController = require('../controllers/ProductController');

app.post('/product', productController.create);

http.createServer(app).listen('3000');
Run Code Online (Sandbox Code Playgroud)

ProductController.js文件

class ProductController {
  constructor(){}

  create(){
   console.log('Checking if the following logs:');
   this.callme();
  }

 callme(){
  console.log('yes');
 }
}
module.exports = new ProductController();
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我收到以下错误消息:

Cannot read property 'callme' of undefined
Run Code Online (Sandbox Code Playgroud)

我已经运行了这个代码,只需要进行一些修改,如下所示,它可以工作.

class ProductController {
  constructor(){}
  create(){
    console.log('Checking if the following logs:');
    this.callme();
  }

  callme(){
    console.log('yes');
  }
}
let product = new ProductController();
product.create();
Run Code Online (Sandbox Code Playgroud)

为什么一个工作而另一个工作?救命!

javascript node.js express ecmascript-6 es6-class

10
推荐指数
2
解决办法
3797
查看次数

JavaScript中的自定义数组类getter

我有一个简单的ES6类,如下所示:

class Ring extends Array {
    insert (item, index) {
        this.splice(index, 0, item);
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想这样做,以便Ring对象的索引包装,所以new Ring(1, 2, 3)[3]返回1,new Ring(1, 2, 3)[-1]返回3,依此类推.这可能在ES6中吗?如果是这样,我将如何实现它?

我已经阅读了代理,它允许完全自定义的getter,但我无法弄清楚如何将代理应用于类.我确实管理了这个:

var myRing = new Proxy (Ring.prototype, {
    get: function (target, name) {
        var len = target.length;
        if (/^-?\d+$/.test(name))
            return target[(name % len + len) % len];
        return target[name];
    }
});
Run Code Online (Sandbox Code Playgroud)

myRing现在是一个支持包装索引的Ring对象.问题是我每次都必须定义像这样的Ring对象.有没有办法将此代理应用于类,以便调用new Ring()返回它?

javascript ecmascript-6 es6-proxy es6-class

10
推荐指数
1
解决办法
657
查看次数

使用ES6类的instanceof继承链不起作用

使用ES6 class语法,我想知道为什么instanceof当有多个继承链时,运算符不适用于继承链?

(可选阅读)

instanceof操作员如何工作?

obj instanceof Constructor,instanceof操作员检查函数的'prototype'属性Constructor是否存在于原型链中obj.如果它存在,请返回true.否则,false.


在下面的代码片段中,BTError继承自Error(1.)并SomeErrorBTError(3.)扩展.
但是,正如我们可以看到从(4),该instanceof操作结果falsenew SomeError() instanceof BTError它在我的理解应该是true.

class BTError extends Error {}
console.log('1.', Reflect.getPrototypeOf(BTError.prototype) === Error.prototype); // 1. true
console.log('2.', new BTError() instanceof Error); // 2. true

console.log('');

class SomeError extends BTError {} …
Run Code Online (Sandbox Code Playgroud)

javascript inheritance class ecmascript-6 es6-class

10
推荐指数
2
解决办法
4280
查看次数

React中是否仍然需要使用自动绑定和属性初始值设定项构造函数

我正在重构一个基于es6类的React组件,该组件使用普通的构造函数,然后绑定方法,并在该构造函数中定义状态/属性.像这样的东西:

class MySpecialComponent extends React.Component {
  constructor(props) {
   super(props)
   this.state = { thing: true }
   this.myMethod = this.myMethod.bind(this)
   this.myAttribute = { amazing: false }
  }

  myMethod(e) {
   this.setState({ thing: e.target.value })
  }
}
Run Code Online (Sandbox Code Playgroud)

我想重构这个,以便我自动绑定函数,并使用属性初始化器的状态和属性.现在我的代码看起来像这样:

class MySpecialComponent extends React.Component {
  state = { thing: true }
  myAttribute = { amazing: false }


  myMethod = (e) => {
   this.setState({ thing: e.target.value })
  }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,我还需要构造函数吗?或道具也是autobound?我本来希望仍然需要构造函数和包含super(props),但我的代码似乎工作,我很困惑.

谢谢

ecmascript-6 reactjs ecmascript-next es6-class

10
推荐指数
2
解决办法
6193
查看次数

不使用class关键字创建自定义元素

这实际上是关于ES6中面向对象模型的问题.但是,我将使用创建新的自定义元素作为示例.

因此,创建一个新的自定义元素的新的和有光泽的(截至今天)方法是根据MDN,Google,当然还有规范customElements.define()来获取标签name,a constructoroptions(这是可选的).列出的所有文档都使用新关键字的变体.classconstructor

假设我不喜欢新的class语法,并且考虑到大多数情况下class是一个合成糖(根据本教程).该规范甚至具体说明了这一点

无参数调用super()必须是构造函数体中的第一个语句,以便在运行任何其他代码之前建立正确的原型链和此值.

通过阅读教程,我出来了,试试是否有可能(也修改和重新学习Javascript的对象模型).

var _extends = function(_parent) {
    var _result = function() {
        _parent.call(this);
    };
    _result.prototype = Object.create(_parent.prototype);
    Object.defineProperty(_result.constructor, 'constructor', {
        enumerable: false,
        writeable: true,
        value: _result
    });

    return _result;
};

customElements.define('foo-bar', _extends(HTMLElement));
console.log(document.createElement('foo-bar'));
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误

错误:正在构造的自定义元素未注册 customElements.

所以我的问题是,是否可以不使用class关键字(也new可能没有)?如果答案是否定的,我是否应该坚持class使用关键字而不是Object.create在将来编写新的Javascript代码时使用?

javascript custom-element es6-class

10
推荐指数
1
解决办法
659
查看次数

为什么我们在React中创建类组件时要扩展React.Component?

我是React新手,我很困惑,日夜不停地思考它,几乎所有的头发都掉下来了,而且还在掉下来,这就是为什么我们在使用类创建组件时总是扩展 React.Component类。

但在功能组件和其他方法中,我们不会做任何这样的事情来将创建的组件推送到React.Component类中。所以主要问题是,什么是React.Component类,为什么我们总是使用extends将新组件作为子组件添加到它,以及为什么我们不能在不使用类组件中的扩展或不扩展React.Component类的情况下在 React Native 中创建组件。那么,React.Component类在幕后的React内部发生了什么,场景是什么?

我将非常非常感谢那个用例子和简单的方法回答我的问题的人。

javascript reactjs react-native es6-class

10
推荐指数
1
解决办法
8400
查看次数

有没有办法将 ES6 私有字段和 Vue 3 的 `reactive` 一起使用?

我有一个使用 ES6 私有字段和公共 getter 的类,我需要使用 Vue 3 的组合 API 进行响应。目前,我的设置看起来像这样:

//store.ts
class Store {
  #userName?: string
  get userName() {
    if(this.#userName !== undefined) return this.#userName
    throw new Error('Cannot get userName before it is defined')
  }

  setUserName(newUserName: string) {
    this.#userName = newUserName
  }
}

const store = reactive(new Store())

export { store }
Run Code Online (Sandbox Code Playgroud)

然后通过提供/注入 API 将该存储实例提供给组件,并像这样使用

<template>
  <span> {{ formattedUserName }} </span>
</template>

<script lang="ts">
import { defineComponent, toRefs, inject } from 'vue'

export default defineComponent({
  setup(){
    const store = inject('storeKey')
    const …
Run Code Online (Sandbox Code Playgroud)

javascript vue.js es6-class vuejs3 vue-composition-api

10
推荐指数
1
解决办法
3043
查看次数

获取类中的所有静态getter

假设我有这个类(我使用它像枚举):

class Color {
    static get Red() {
        return 0;
    }
    static get Black() {
        return 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么类似Object.keys拿到['Red', 'Black']

我正在使用Node.js v6.5.0,这意味着某些功能可能会丢失.

javascript getter node.js ecmascript-6 es6-class

9
推荐指数
1
解决办法
3203
查看次数