相关疑难解决方法(0)

箭头函数与函数声明/表达式:它们是等效/可交换的吗?

规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.

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)

javascript ecmascript-6 arrow-functions

449
推荐指数
2
解决办法
12万
查看次数

什么是"new.target"?

ECMAScript 2015规范提到关键字(或单词?)new.target正好3次 - 在14.2.3中 1次:

通常,Contains不会查看大多数函数表单但是,Contains用于检测ArrowFunction中的new.target,this和super用法.

14.2.16中两次:

ArrowFunction不为arguments,super,this或new.target定义本地绑定.对ArrowFunction中的参数,super,this或new.target的任何引用 都必须解析为词汇封闭环境中的绑定

MDN提到它,但非常模糊,页面不完整.

巴别塔似乎不支持它.尝试在函数(箭头或其他)中使用new.target时出现语法错误.

它是什么,它应该如何使用?

javascript ecmascript-6

25
推荐指数
2
解决办法
6139
查看次数

如何在javascript中使用代理来捕获构造函数同时维护原型链?

我想创建一个构造函数对象,其继承正常工作,但捕获构造函数以便我可以操作实例对象。使用Proxy() 几乎解决了这个问题,但它似乎搞砸了继承。请注意以下没有代理的示例:

> const B = function() {}
undefined
> B.name
'B'
> class C extends B {}
[Function: C]
> B.prototype == C.prototype.__proto__
true
> var instance = new C()
undefined
> C.prototype == instance.__proto__
true
> instance.__proto__
C {}
Run Code Online (Sandbox Code Playgroud)

现在,如果我向 capture 添加一个代理construct(target,args),它将正确捕获构造函数,但它不会像没有代理那样完全保留内容。请注意,构造函数所做的只是向控制台打印一条消息,记录其捕获。但否则(我认为)它应该做出相同的反应。但是,当我创建一个类来扩展代理函数时,似乎扩展函数完全丢失了。请注意,最后四行给出的结果与上面不同。

> const handler = { construct(target,args) {
... console.log('Captured!'); return new target(...args); } }
undefined
> const proxy_B = new Proxy(B, handler)
undefined
> proxy_B.name
'B'
> class C2 extends proxy_B {} …
Run Code Online (Sandbox Code Playgroud)

javascript proxy constructor ecmascript-6

5
推荐指数
1
解决办法
830
查看次数