简体   繁体   中英

Is it normal to not pass variable as parameter in Javascript?

I came across such code in Javascript and became quite puzzled as I come from C++/Python background:

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
  }

  ...

}

It seems like you can just use variable that is outside of a function. I understand that that is how JS works but I am not sure if that is what people usually do, just use variable from outside and not pass as parameter. Is that a standard and normal practice?

The following looks quite impossible to pass variable as parameter to function:

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;

Is that a standard and normal practice?

Generally no, but there are exceptions. (for example having the entire state of the application in a variable).

Classes and functions are meant to be reused.

If your function (or class) relies on global variables then it will be hard to reuse and test.

Bottom line is : avoid it whenever possible.

In React it's definitely normal to have a list of fake data set in the state like in your example. You usually would import it from a different file though with the import syntax. But for better testability of your components, you are better off avoiding importing external libraries and instead passing it as parameters.

It's possible, but should be used with caution. As you can imagine, if everyone uses global variables, you can very easily end up with name collisions. Also, global variables are never garbage collected, so you risk littering the memory as well.

Generally, if you write a framework in JavaScript, you'll publish one global variable, which sort of serves as the "namespace" of your framework: Rx , d3 , $ , Handlebars , etc. These are usually the same as the name of the framework itself, so collisions are unlikely. Everything else is then defined within that object, eg Handlerbars.compile() and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM