我可以从不同的范围调用匿名自调用函数吗?

时间:2016-03-16 10:06:32

标签: javascript reactjs

我使用的是ReactJS。我想调用hello()函数。我得到了#34; Uncaught ReferenceError:hello未定义"错误。我该如何解决?

的index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

    <script src="sample.js"></script>
  </head>
  <body>
    <div id="content"></div>
    <script type="text/babel">
      var CommentBox = React.createClass({
        handleClick: function(){
          console.log(hello());
        },
        render: function() {
          return (
            <a onClick={this.handleClick}>click me</a>
          );
        }
      });
      ReactDOM.render(
        <CommentBox />,
        document.getElementById('content')
      );
    </script>
  </body>
</html>

sample.js

$(function(){
  function hello() {
    return "Hi";
  }
});

1 个答案:

答案 0 :(得分:0)

修正了它。感谢

var O = (function(){
  function hello() {
    return "Hi";
  }
  return {hello: hello};
})();

handleClick: function(){
  console.log(O.hello());
}