我正在阅读ScrollListView的源代码,在几个地方我看到了使用() => {}.
如在线25,
this.cellReorderThreshold = () => {
var ratio = (this.CELLHEIGHT*this.cellsWithinViewportCount)/4;
return ratio < this.CELLHEIGHT ? 0 : ratio;
};
Run Code Online (Sandbox Code Playgroud)
第31行,
this.container.addEventListener('scroll', () => this.onScroll(), false);
Run Code Online (Sandbox Code Playgroud)
第88行.
resizeTimer = setTimeout(() => {
this.containerHeight = this.container.offsetHeight;
}, 250);
Run Code Online (Sandbox Code Playgroud)
这是一个简写function,如果它有任何不同,怎么样?
我在互联网上找到了关于名称,箭头功能和胖箭头功能的信息,但没有关于它们之间有什么不同的信息.
有什么不同吗?
我有一个箭头函数,看起来像这样(简化):
const f = arg => { arg.toUpperCase(); };
Run Code Online (Sandbox Code Playgroud)
但是当我打电话给它时,我得到undefined:
console.log(f("testing")); // undefined
Run Code Online (Sandbox Code Playgroud)
为什么?
例:
const f = arg => { arg.toUpperCase(); };
console.log(f("testing"));Run Code Online (Sandbox Code Playgroud)
(注意:对于上面箭头函数的特定问题,这是一个干净的,规范的dupetarget .)
随着阵列
['/social/swipes/women', '/social/swipes/men', '/upgrade/premium'];
Run Code Online (Sandbox Code Playgroud)
我想构建一个看起来像这样的地图对象:
{
'social': {
swipes: {
women: null,
men: null
}
},
'upgrade': {
premium: null
}
}
Run Code Online (Sandbox Code Playgroud)
const menu = ['/social/swipes/women', '/social/likes/men', '/upgrade/premium'];
const map = {};
const addLabelToMap = (root, label) => {
if(!map[root]) map[root] = {};
if(!map[root][label]) map[root][label] = {};
}
const buildMenuMap = menu => {
menu
// make a copy of menu
// .slice returns a copy of the original array
.slice()
// convert the string to an array by splitting …Run Code Online (Sandbox Code Playgroud)javascript arrays javascript-objects ecmascript-6 arrow-functions
假设我们有这样的组件
const Example = () => {
const [counter, setCounter] = useState(0);
const increment = () => setCounter(counter => counter + 1);
return (
<div>
<Button onClick={increment} />
<div>{counter}</div>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
当我将onClick处理程序作为箭头函数传递时,我eslint抛出一个警告:
error JSX props should not use arrow functions react/jsx-no-bind
Run Code Online (Sandbox Code Playgroud)
正如我从这篇文章的答案中读到的:https : //stackoverflow.com/questions/36677733/why-shouldnt-jsx-props-use-arrow-functions-or-bind# :~: text=Why%20you%20shouldn 't%20use,previous%20function%20is%20garbage%20collected。
简短的回答是因为每次都会重新创建箭头函数,这会损害性能。这篇文章提出的一个解决方案是用空数组包装在useCallback钩子中。当我改成这个时,eslint 警告就真的消失了。
const Example = () => {
const [counter, setCounter] = useState(0);
const increment = useCallback(() => setCounter(counter => counter + …Run Code Online (Sandbox Code Playgroud) 这是我的Angular代码中的普通ES5函数,它可以工作:
app.run(function($templateCache){ $templateCache.put('/some','thing') });
Run Code Online (Sandbox Code Playgroud)
我想将它转换为ES6箭头功能
app.run($templateCache => $templateCache.put('/some','thing'));
Run Code Online (Sandbox Code Playgroud)
但它给出了错误
Uncaught Error: [$injector:unpr] Unknown provider: '/some'Provider <- '/some'
http://errors.angularjs.org/1.4.6/$injector/unpr?p0='%2Fsome'Provider%20%3C-%20'%2Fsome'
REGEX_STRING_REGEXP @ angular.js:68
(anonymous function) @ angular.js:4287
getService @ angular.js:4435
(anonymous function) @ angular.js:4292
getService @ angular.js:4435
invoke @ angular.js:4467
(anonymous function) @ angular.js:4297
forEach @ angular.js:336
createInjector @ angular.js:4297
doBootstrap @ angular.js:1657
bootstrap @ angular.js:1678
angularInit @ angular.js:1572
(anonymous function) @ angular.js:28821
trigger @ angular.js:3022
eventHandler @ angular.js:3296
Run Code Online (Sandbox Code Playgroud)
ES6箭头功能是否与Angular不兼容?
编辑:我想也许Angular无法推断名称$templateCache,因此无法注入它,但后来我将其记录到控制台,它确实显示正确:
app.run($templateCache=>console.log($templateCache));
// =>
// Object {}
// destroy: function() …Run Code Online (Sandbox Code Playgroud) javascript angularjs ecmascript-6 angularjs-injector arrow-functions
我通常会尝试将流函数类型与其实现分开.我写的时候可读性稍高一些:
type Fn = string => string;
const aFn: Fn = name => `hello, ${ name }`;
Run Code Online (Sandbox Code Playgroud)
而不是:
const aFn = (name: string): string => `hello, ${ name }`;
Run Code Online (Sandbox Code Playgroud)
使用泛型类型时,我们可以写:
const j= <T>(i: T): T => i;
const jString: string = j('apple'); // ?
const jNumber: number = j(7); // ?
Run Code Online (Sandbox Code Playgroud)
但是如何将这种类型与函数表达式分开?
type H<T> = (input: T) => T;
const h:H<*> = i => i; // --> WHAT SHOULD GO FOR '*'?
const hString: string = h('apple'); // X error …Run Code Online (Sandbox Code Playgroud) javascript generics parameterized-types flowtype arrow-functions
我试图用箭头功能node v0.10.33下Ubuntu 14.04(我运行与节点--harmony标志),但我得到这个错误:
console.log( [1,2,3,4].map(x => x*x) );
^
SyntaxError: Unexpected token >
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
Run Code Online (Sandbox Code Playgroud) 我有这个代码
async function addFiles(dir,tree) {
return (await readDir(dir))
.map(async (name) => {await readDir(dir); return name;})
}
Run Code Online (Sandbox Code Playgroud)
但不幸的是,它只返回了一堆承诺,因为没有等待map中的异步函数.我想知道是否有任何方法可以等待上面代码中的映射函数.
通过 webpack 运行我的代码后,它包含箭头函数。我需要代码在 ie11 中工作,所以我需要摆脱箭头函数。
我正在为所有 .js 文件使用 babel-loader。
我写了一个加载器来检查箭头函数的代码,并在 babel-loader 之后运行它,但没有得到任何箭头函数,所以我知道 babel 的输出是好的。
我还尝试了 babel-polyfill 和用于转换箭头功能的 babel 插件。
我知道 babel-loader 输出好的代码,我怀疑它可能是一个插件,但我不能只是禁用它们进行测试,因为这会破坏构建。
开发中使用的 Webpack 插件:
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
Run Code Online (Sandbox Code Playgroud)
这个问题也出现在 prod 中,但是在 …
javascript internet-explorer-11 webpack babeljs arrow-functions
arrow-functions ×10
javascript ×9
ecmascript-6 ×5
babeljs ×2
angularjs ×1
arrays ×1
async-await ×1
flowtype ×1
generics ×1
node.js ×1
reactjs ×1
typescript ×1
usecallback ×1
webpack ×1