[英]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.