我将代码从 es5 类原型表示更改为 es6 类表示。但我收到错误
这是迁移到 es6 之前和之后的代码
ES5语法
function RoutingScreen (context) {
Object.assign(this, {route} = context)
}
RoutingScreen.prototype.onEnter = function(state) {
state.scaning = false
state.status = 'Scan to continue'
curState = states.init
};
Run Code Online (Sandbox Code Playgroud)
ES6语法
class RoutingScreen{
constructor(context){
Object.assign(this, {route}= context)
}
onEnter(state){
state.scaning = false
state.status = 'Scan to continue'
curState = states.init
}
}
Run Code Online (Sandbox Code Playgroud)
我收到这样的错误
类型错误:代理上的“设置”:陷阱为属性“扫描”返回错误
但es5代码工作正常。
我使用的是节点版本8.1
我不知道我在这里做错了什么。
这是我调用这些方法的地方
function setRoute (newRoute) {
var r = currentRoute()
console.log('changeRoute from ' + (r?r.route:'""') + ' to ' + …Run Code Online (Sandbox Code Playgroud) class TestObject {
constructor(value) {
if (value === null || value === undefined) {
throw new Error('Expect a value!');
}
}
}
describe('test the constructor', () => {
test('it works', () => {
expect(() => {
new TestObject();
}).toThrow();
});
test('not work', () => {
expect(new TestObject()).toThrow();
});
});
Run Code Online (Sandbox Code Playgroud)
2这里的测试用例,一个工作,另一个不工作.
该消息的失败消息not work如下:
●测试构造函数>不工作
期待一个价值!
Run Code Online (Sandbox Code Playgroud)at new TestObject (tests/client/utils/aaa.test.js:4:11) at Object.<anonymous> (tests/client/utils/aaa.test.js:17:12) at Promise (<anonymous>) at <anonymous> at process._tickCallback (internal/process/next_tick.js:188:7)
为什么我需要在函数调用中包装该调用,当函数只返回一个普通值,甚至是一个promise时,我们不需要包装,我们可以用它async/await来检查expect()而不是在里面创建一个函数expect().
这里发生了什么?
感谢您阅读我的文章,我在代码中遇到此错误:“类扩展值#不是构造函数或null”这是我的代码,我正在尝试导出/导入类。
monster.js:
const miniMonster = require("./minimonster.js");
class monster {
constructor(options = { name }, health) {
this.options = options;
this.health = 100;
this.heal = () => {
return (this.health += 10);
};
}
}
let bigMonster = new monster("Godzilla");
console.log(bigMonster);
console.log(bigMonster.heal());
let mini = new miniMonster("Demon");
console.log(mini);
console.log(mini.heal());
module.exports = monster;
Run Code Online (Sandbox Code Playgroud)
minimonster.js:
const monster = require("./monster.js");
class miniMonster extends monster {
constructor(options) {
super(options);
this.health = 50;
this.heal = () => {
return (this.health += 5);
};
}
}
let …Run Code Online (Sandbox Code Playgroud) 在 ES6 中是否有可能实现这一点——或者如果不能的话是否有一个很好的解决方案(看起来很可能):
class Parent {
constructor() {
console.log(this.name);
}
}
class Child extends Parent {
name = "Child Name";
}
const c = new Child();
// Should console.log "Child Name";
Run Code Online (Sandbox Code Playgroud)
(来自 Python,它完全可以工作!)
我正在 vue 项目中编写带有私有属性/方法的 ES6 类。并使用 eslint 对代码进行 lint。下面是示例类:
class TestClass {
constructor(value) {
this.#privateProperty = value
this.#privateMethod(this.#privateProperty)
}
#privateProperty = undefined
// lint error raised at below line
#privateMethod(value) {
this.e = value
console.log(this.e)
}
}
Run Code Online (Sandbox Code Playgroud)
vue 项目由@vue/cli 4.1.2 创建。以下是有关该项目的一些配置:
babel.config.js:
module.exports = {
presets: ['@vue/cli-plugin-babel/preset'],
plugins: [
['@babel/plugin-proposal-class-properties', { loose: true }],
['@babel/plugin-proposal-private-methods', { loose: true }]
]
}
Run Code Online (Sandbox Code Playgroud)
包.json:
{
"name": "demo-project",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"test:unit": "vue-cli-service test:unit",
"lint": …Run Code Online (Sandbox Code Playgroud) 这个问题是关于chrome浏览器的。
我正在尝试动态导入定义为类的 javascript 模块。
// data-table.js
export class DataTable extends HTMLElement{
constructor() {
super();
}
static get tagName() {
return 'data-table';
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有办法获取目标代码中导入的类的名称。这是我的目标代码,不起作用。
// router.js
...//some code
if(route === matched){
// dynamically import the component
import(route.component)
.then( module => {
// anyway to get classname DataTable here??
})
};
...//rest of the code
Run Code Online (Sandbox Code Playgroud)
这是明显有效的实现,(因为我对模块类名称进行了硬编码)
// router.js
...//some code
if(route === matched){
// dynamically import the component
import("components/data-table.js")
.then( {DataTable} => {
cost t = DataTable.tagName;
// code to handle …Run Code Online (Sandbox Code Playgroud) 如果我在类中只声明一个私有方法,则 ESLINT 编译时不会发出警告,但是...\nESLINT 会为我在同一类中声明的每个新私有方法发出一个额外警告。
\n例如,ESLINT 对于如下声明的类发出 2 个警告:
\nclass Clazz {\n #methodOne() { /*...*/ }\n #methodTwo() { /*...*/ }\n #methodThree() { /*...*/ }\n}\nRun Code Online (Sandbox Code Playgroud)\nESLINT 输出:
\nWARNING Compiled with 1 warning 10:14:26 PM\n\nModule Warning (from ./node_modules/eslint-loader/index.js):\n\n/Users/***/Clazz.js\n 3:3 error Duplicate name \'\' no-dupe-class-members\n 4:3 error Duplicate name \'\' no-dupe-class-members\n\n\xe2\x9c\x96 2 problems (2 errors, 0 warnings)\nRun Code Online (Sandbox Code Playgroud)\n我想知道我是否做错了什么,或者我应该忽略这些警告。
\n包.json:
\nWARNING Compiled with 1 warning 10:14:26 PM\n\nModule Warning (from ./node_modules/eslint-loader/index.js):\n\n/Users/***/Clazz.js\n 3:3 error Duplicate name \'\' no-dupe-class-members\n 4:3 …Run Code Online (Sandbox Code Playgroud) 在 javascript 中创建类时,您可以通过访问函数的prototype.
function Foo() {
}
Foo.prototype.get = function() {
return this._value;
}
Foo.prototype._value = 'foo value';
var foo = new Foo();
console.log(foo.get()); // logs "foo value"
Run Code Online (Sandbox Code Playgroud)
如何使用 ecmascript 6 达到类似的效果class?
// this doesn't work
class Bar {
get() {
return this._value;
}
// how to declare following default value properly?
_value: "bar value"
}
var bar = new Bar();
console.log(bar.get()); // logs undefined
Run Code Online (Sandbox Code Playgroud) 我对创建 API 包装器并使用 es6 类从 axios 进行扩展很感兴趣。这怎么可能?axios 有一个方法 .create() 可以让你生成一个新的 axios 对象
class Api extends Axios {
constructor(...args){
super(..args)
this.defaults.baseURL = 'https://api.com'
}
cancelOrder (id) {
return this.put(`/cancel/order/${id}`)
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以访问这个let instance = axios.create()。
有什么想法吗?
尝试1
import axios from 'axios'
const Axios = axios.create()
class Api extends Axios {
constructor (...args) {
super(...args)
this.defaults.baseURL = 'https://api.com'
}
cancelOrder (id) {
return this.put(`/cancel/order/${id}`)
}
}
let api = new Api()
api.cancelOrder('hi')
.then(console.log)
.catch(console.log)
Run Code Online (Sandbox Code Playgroud)
尝试2
import axios from 'axios'
class …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 ES6 类进行热代码重载。我需要能够修改类的构造函数,而不需要用新的类替换该类(因为其他人可能会引用它)。
然而,我发现类对象看起来好像有一些对其最初定义的构造函数的内部引用;用 实例化该类new不会查找该类 constructor 或prototype.constructor该类。
例子:
class OldC { constructor() { console.log("old"); } }
class NewC { constructor() { console.log("new"); } }
OldC.prototype.constructor = NewC.prototype.constructor;
OldC.constructor = NewC.constructor;
new OldC();Run Code Online (Sandbox Code Playgroud)
--->“旧”
(更新所有其他方法都可以正常工作;这只是我遇到问题的构造函数。)
考虑到可以通过 找到构造函数[[prototype]],我还添加了以下内容:
Object.setPrototypeOf(OldC, Object.getPrototypeOf(NewC));
Object.setPrototypeOf(OldC.prototype, Object.getPrototypeOf(NewC.prototype));
Run Code Online (Sandbox Code Playgroud)
这也没有帮助(鉴于没有发生子类化,我不会期望它会发生)。
毕竟,检查 OldC 表明原型属性完全符合我的预期,OldC.prototype.constructor是新的。但是,构造 OldC 的实例仍然会调用原始构造函数。
这是怎么回事?我该如何解决?
es6-class ×10
javascript ×10
ecmascript-6 ×6
eslint ×2
axios ×1
es6-modules ×1
jest ×1
node.js ×1
prototype ×1