gpt4 book ai didi

javascript - 使用 BabelJs 转译时如何忽略一段代码?

转载 作者:行者123 更新时间:2023-11-30 10:01:48 25 4
gpt4 key购买 nike

我正在尝试引用 this在 ES2015 中,使用 Babeljs。我遇到的这个问题是 Babeljs 一直在移动 this超出范围进入外部范围。这破坏了代码。我希望 Babeljs 有评论,或者我可以使用某种 block 符号来让它忽略代码,这样它就不会被转译。

如果那里有 Mongoose 大师,也许还有另一种方法来访问有问题的属性和函数 (this.isNew || this.isModified('email'))。

这是 ES2015 代码。

setDuplicateEmailValidation(){
this.schema.path('email').validate((email, fn) => {
let User = mongoose.model('User');

// Check only when it is a new user or when email field is modified
if (this.isNew || this.isModified('email')) {
User.find({ email: email }).exec((err, users) => {
fn(!err && users.length === 0);
});
} else fn(true);
}, 'Email already exists');
}

在 if 语句中 if (this.isNew || this.isModified('email'))预编译代码引用了 this . validate()的范围|很重要,因为在此范围内我可以访问 Mongoosejs's Document应用程序接口(interface)。一旦代码移出 validate() scope 我不再有权访问 Document API。

转译后的代码。

function setDuplicateEmailValidation() {
var _this = this;
this.schema.path('email').validate(function (email, fn) {
var User = _mongoose2['default'].model('User');

// Check only when it is a new user or when email field is modified
if (_this.isNew || _this.isModified('email')) {
User.find({ email: email }).exec(function (err, users) {
fn(!err && users.length === 0);
});
} else fn(true);
}, 'Email already exists');
}
}

在此代码中,您会注意到 if 语句引用了验证函数范围之外的变量 ( if (_this.isNew || _this.isModified('email')) )。由于这个(没有双关语意)移动,我失去了对 Mongoosejs 文档 API 的访问权限。

如有任何建议,我们将不胜感激。

最佳答案

不要使用 arrow function ,只需使用 function 关键字:

this.schema.path('email').validate(function (email, fn) {

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value.

强调我的。这意味着箭头函数内部的 this 将是箭头函数外部相同词法上下文中的 this 。这是故意的,不同于 function 语法。

关于javascript - 使用 BabelJs 转译时如何忽略一段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31226150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com