【发布时间】:2016-10-24 16:45:46
【问题描述】:
我有一个非常小的 ES6 代码:
var name = "MyName";
var version = "1.2.3";
var theThing = {
name,
version,
run: () => {
console.log(`You're using ${this.name}@${this.version}`);
}
};
theThing.run();
当我在浏览器控制台(chrome 53)中运行它时,我得到了预期的结果:You're using MyName@1.2.3 被记录到控制台。两个模板字符串都与缩短的对象文字语法一起使用。
但是,当我尝试使用 gulp/babel 将此代码转换为 ES5 时,使用最基本的设置(取自 here):
const gulp = require('gulp');
const babel = require('gulp-babel');
gulp.task('default', () => {
return gulp.src('src/app.js')
.pipe(babel({
presets: ['es2015']
}))
.pipe(gulp.dest('dist'));
});
我得到以下输出:
"use strict";
var name = "MyName";
var version = "1.2.3";
var theThing = {
name: name,
version: version,
run: function run() {
console.log("You're using " + undefined.name + "@" + undefined.version);
}
};
theThing.run();
如您所见,它调用的是undefined.name 而不是this.name,我完全不知道为什么this 被undefined 取代。当然,这段代码并没有按预期工作:
VM329:8 Uncaught TypeError: Cannot read property 'name' of undefined(…)
并且不符合 ES6(在 chrome53 中 ES6 的原始实现可以正常工作)。
你也可以在Babel REPL看到这个问题。
我做错了什么 - 还是 babel 中的错误?
【问题讨论】:
标签: javascript syntax ecmascript-6 babeljs