简体   繁体   English

在Javascript中不将变量作为参数传递是正常的吗?

[英]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: 我碰巧用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
  }

  ...

}

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. 我知道这就是JS的工作方式,但是我不确定这是否是人们通常所做的,只是从外部使用变量而不将其作为参数传递。 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. 在React中,像您的示例一样,在状态中设置一组伪数据绝对是正常的。 You usually would import it from a different file though with the import syntax. 尽管通常使用import语法,您通常会从其他文件中导入它。 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. 通常,如果您使用JavaScript编写框架,则会发布一个全局变量,该变量用作框架的“命名空间”: Rxd3$Handlebars等。这些通常与的名称相同框架本身,因此不会发生冲突。 Everything else is then defined within that object, eg Handlerbars.compile() and so on. 然后,其他所有内容都在该对象中定义,例如Handlerbars.compile()等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将变量作为参数传递给javascript函数 - Pass variable as a parameter in javascript function 将 javascript 变量传递给 url 参数 - Pass javascript variable to url parameter 如何在JAVASCRIPT中按变量传递参数 - How to pass parameter by variable in JAVASCRIPT 如何将有角的$ scope变量传递给JavaScript正态变量 - How to pass of angular $scope variable to JavaScript normal variable 在嵌入式 Ruby 中使用 JavaScript 将变量作为参数传递 - Using JavaScript in embedded Ruby to pass a variable as a parameter Javascript从函数返回变量并作为参数传递 - Javascript return variable from function and pass as parameter 使用参数(JavaScript)将变量直接传递到getElementById - Pass a variable directly into getElementById using the parameter (JavaScript) 如何在javascript中通过引用传递全局变量作为参数 - How to pass a global variable as parameter by reference in javascript 在Javascript中,是否可以将变量传递给<script> “src” parameter? - In Javascript, is it possible to pass a variable into <script> “src” parameter? 获取Javascript变量并在AJAX调用中作为参数传递 - Fetching the Javascript Variable and pass as a parameter in AJAX call
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM