[英]Is it normal to not pass variable as parameter in Javascript?
我碰巧用Javascript编写了这样的代码,并且由于来自C ++ / Python背景而感到困惑:
const list = [
{
title: 'React',
url: 'https://facebook.github.io/react/',
author: 'Jordan Walke',
num_comments: 3,
points: 4,
objectID: 0,
},
...
];
class App extends Component {
constructor(props) {
super(props);
# leanpub-start-insert
this.state = {
list: list,
};
# leanpub-end-insert
}
...
}
似乎您只能使用函数外部的变量。 我知道这就是JS的工作方式,但是我不确定这是否是人们通常所做的,只是从外部使用变量而不将其作为参数传递。 这是标准做法吗?
下面看起来很难将变量作为参数传递给函数:
import React, { Component } from 'react';
import './App.css';
const list = [
{
title: 'React',
url: 'http://facebook.github.io/react',
author: 'Jordan Walke',
num_comments: 3,
points: 4,
objectID: 0,
},
{
title: 'Redux',
url: 'https://github.com/reactjs/redux',
author: 'Dan Abramov, Andrew Clark',
num_comments: 2,
points: 5,
objectID: 1,
}
]
const isSearched = searchTerm => item =>
item.title.toLowerCase().includes(searchTerm.toLowerCase());
class App extends Component {
constructor(props) {
super(props);
this.state = {
list: list,
searchTerm: '',
}
this.onDismiss = this.onDismiss.bind(this);
this.onSearchChange = this.onSearchChange.bind(this);
}
onDismiss(id) {
const isNotID = item => item.objectID !== id;
const updatedList = this.state.list.filter(isNotID);
this.setState({ list: updatedList });
}
onSearchChange(event) {
this.setState({ searchTerm: event.target.value });
}
render() {
return (
<div className="App">
<form>
<input
type="text"
onChange={this.onSearchChange}
/>
</form>
{this.state.list.filter(isSearched(this.state.searchTerm)).map(item =>
<div key={item.objectID}>
<span>
<a href={item.url}>{item.title}</a>
</span>
<span>{item.author}</span>
<span>{item.num_comments}</span>
<span>{item.points}</span>
<span>
<button onClick={() => this.onDismiss(item.objectID)} type="button">
Dismiss
</button>
</span>
</div>
)}
</div>
)
}
}
export default App;
这是标准做法吗?
通常没有,但是也有例外。 (例如,将应用程序的整个状态包含在一个变量中)。
类和函数将被重用。
如果您的函数(或类)依赖于全局变量,那么将很难重用和测试。
底线是 :尽可能避免使用。
在React中,像您的示例一样,在状态中设置一组伪数据绝对是正常的。 尽管通常使用import
语法,您通常会从其他文件中导入它。 但是,为了使组件具有更好的可测试性,最好避免导入外部库,而是将其作为参数传递。
有可能,但应谨慎使用。 可以想象,如果每个人都使用全局变量,则很容易导致名称冲突。 此外,全局变量绝不会被垃圾回收,因此您也有可能乱丢内存。
通常,如果您使用JavaScript编写框架,则会发布一个全局变量,该变量用作框架的“命名空间”: Rx
, d3
, $
, Handlebars
等。这些通常与的名称相同框架本身,因此不会发生冲突。 然后,其他所有内容都在该对象中定义,例如Handlerbars.compile()
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.