规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.
ES2015中的箭头功能提供了更简洁的语法.我现在可以用箭头功能替换所有函数声明/表达式吗?我需要注意什么?
例子:
构造函数
function User(name) {
this.name = name;
}
// vs
const User = name => {
this.name = name;
};
Run Code Online (Sandbox Code Playgroud)
原型方法
User.prototype.getName = function() {
return this.name;
};
// vs
User.prototype.getName = () => this.name;
Run Code Online (Sandbox Code Playgroud)
对象(文字)方法
const obj = {
getName: function() {
// ...
}
};
// vs
const obj = {
getName: () => {
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
回调
setTimeout(function() {
// ...
}, 500);
// vs
setTimeout(() => {
// ...
}, …Run Code Online (Sandbox Code Playgroud) 给出一个简单的类
class Foo {
constructor(x) {
if (!(this instanceof Foo)) return new Foo(x);
this.x = x;
}
hello() {
return `hello ${this.x}`;
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以在没有new关键字的情况下调用类构造函数?
用法应该允许
(new Foo("world")).hello(); // "hello world"
Run Code Online (Sandbox Code Playgroud)
要么
Foo("world").hello(); // "hello world"
Run Code Online (Sandbox Code Playgroud)
但后者失败了
Cannot call a class as a function
Run Code Online (Sandbox Code Playgroud) 我在编程语言中的一个小问题是获取在构造函数中传递的参数,并将它们直接分配给类中的字段,命名与我在构造函数中给它们的参数相同,如下所示:
class A {
constructor(a, b) {
this.a = a;
this.b = b;
etc...
}
}
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,我想我可以创建一个函数,该函数采用类中现有的键,以及动态的参数,如下所示:
function test(values) {
Object.keys(this).map((x,i) => this[x] = values[i]);
}
class ChildObj {
a1;
a2;
constructor() {
test.call(this, arguments);
}
}
Run Code Online (Sandbox Code Playgroud)
这很完美,但是,我想通过消除重复的构造函数声明来使它更方便,因为在我的应用程序中,我有很多这样声明的类,并且相同的重复 3 行已经开始代表源代码的重要部分代码。
我的第一直觉是使用继承,但是字段是子对象的属性,因此对父对象不可见。然后我尝试修改类的构造函数,它与所有相关类的数组配对可以动态完成,但是更改类的构造函数似乎不可能,正如我所尝试的
A.constructor = function() {
test.call(this, arguments);
}
A.prototype.constructor = function() {
test.call(this, arguments);
}
Run Code Online (Sandbox Code Playgroud)
暂时,我转而尝试将我的对象定义为函数,但这遇到了访问函数参数名称的问题,而这显然只能通过对源代码进行正则表达式处理,而我宁愿避免这种情况。
-----PS:-------
我取得了一些突破,设法通过让父级构造子级的副本将子键传递给父级,但在那里截断递归,如下所示:
A.constructor = function() {
test.call(this, arguments);
}
A.prototype.constructor = function() {
test.call(this, arguments);
}
Run Code Online (Sandbox Code Playgroud)
但是,看起来其他东西已经损坏,因为它仍然没有将值分配给结果对象。
-----结束 PS ---------
所以,总结一下:在 Javascript 中是否有可能动态分配这样的构造函数,如果没有,是否有另一种方法可以使用像这样的普通构造函数创建对象?谢谢你。