如何定义函数并仅在需要时使用

时间:2018-02-02 15:30:11

标签: javascript jquery

我正在开发一个MVC应用程序。到目前为止,我将整个JS代码写入视图中。这违反了良好做法。现在我试图将部分代码移动到单独的文件中,然后将其包含在视图中。这是代码示例:

var scripts = function() {
  var _foo = function foo(){
    // ...
  }

  return {
    init: function () {
      _foo ();
    }
  };
}();

jQuery(document).ready(function() {
  scripts.init();
});

这就是我的.js文件的样子和工作方式。但是如果我想用参数定义函数如下:

var scripts = function() {
  var _foo = function foo(params) {
    // ...
  }

  return {
    init: function () {
      _foo ();
      _foo ;
    }
  };
}();

我在控制台中收到错误'触发函数时未定义_foo'。有没有办法定义函数并在需要时使用它?

3 个答案:

答案 0 :(得分:1)

  

我在控制台中收到错误'触发函数时未定义_foo'。

目前还不清楚你的意思。在下面的代码中, Col1 Col2 Col3 1 2 3.0 3 3 0.9 3 1 1.3 4 nan 1.3 是匿名函数中的局部变量,它将对象_foo分配给init: function(){ ...变量。因此,通过调用scripts,可以访问和调用scripts.init(),如下所示。

但是,如果直接调用_foo,则不会在全局范围内定义和访问它(因为它是匿名函数中的私有局部变量)。

_foo()

  

有没有办法定义函数并在需要时使用它?

当然,您可以将其作为var scripts = function() { var _foo = function foo(params) { // ... console.log('_foo called'); } return { init: function () { _foo (); } }; }(); scripts.init(); _foo(); // will not work, as it is not accessible in global scope变量的方法进行访问,如下所示:

scripts

答案 1 :(得分:0)

有几种方法可以在对象中执行功能。作为“脚本”对象的替代方案,我在这里使用原型和makeClassStrict(来自此网站上的其他问题)https://stackoverflow.com/a/17588082/125981

这会创建一个名为“MyClass”的对象,我可以在其中添加函数,例如带有参数的newFoo函数。我还说明了帖子中的init函数概念,它允许我在实例创建时将参数传递给init,只需将参数传递给MyClass()作为var newInstanceThing = MyClass("fred");,例如

另请注意,我添加了一个名为origFoo

的函数

/* JavaScript makeClass example */
/* http://ejohn.org/blog/simple-class-instantiation/ */
// makeClassStrict - By Hubert Kauker 
// original by John Resig (MIT Licensed).
function makeClassStrict() {
  var isInternal, instance;

  var constructor = function(args) {
    // Find out whether constructor was called with 'new' operator.
    if (this instanceof constructor) {
      // When an 'init' method exists, apply it to the context object.
      if (typeof this.init == "function") {
        // Ask private flag whether we did the calling ourselves.
        this.init.apply(this, isInternal ? args : arguments);
      }
    } else {
      // We have an ordinary function call.

      // Set private flag to signal internal instance creation.
      isInternal = true;
      instance = new constructor(arguments);
      isInternal = false;
      return instance;
    }
  };

  return constructor;
}
var MyClass = makeClassStrict(); // create object
MyClass.prototype = {
  origFoo: function(mything) {
    return mything;
  }
}
//  add init to my new "MyClass" prototype, could be in object above also
MyClass.prototype.init = function(newText, newThing) {
  this.someText = newText == undefined ? 'defaultText' : newText;
  this.newThing = newThing == undefined ? 'defaultThing' : newThing;
  this.gobble = 'turkey';
  this.cracker = 'cheese';
}
// add a new function newFoo
MyClass.prototype.newFoo = function(foome, foometwice) {
  this.foo = foome;
  this.foo2 = foometwice;
}
// add a new string object to the prototype
MyClass.prototype.otherText = 'otherstuff';

// create instance of my class with parameter for newText
var trustme = MyClass('trustmedude'); // init gets used
console.log(trustme.someText + ":" + trustme.newThing);
console.log(trustme.origFoo("wilber was here"));

// create instance with parameter for newText and newThing
var iam = MyClass('some new text', 'mything');
console.log(trustme.newThing); // logs defaultThing
console.log(iam.someText); //logs "some new text"
iam.someText = 'hi fred'; // change it for this instance
console.log(iam.someText); //logs "hi fred"
console.log(iam.otherText); // logs "otherstuff" set above
console.log(iam.newThing); //logs "mything"
// note don't use the prototype directly
console.log(MyClass.someText); //logs undefined
console.log(MyClass.otherText); //logs undefined
// these are in the instance
console.log(iam.cracker + iam.gobble); //logs "cheeseturkey"
console.log(iam.hasOwnProperty("someText")); //logs true
// show that they ARE different in each instance
console.log(iam.gobble + ":" + trustme.gobble + ":" + trustme.someText + ":" + iam.someText);
// do our foo function and properties stuff
iam.newFoo("fooby", 123);
console.log(iam.foo, iam.foo2);

答案 2 :(得分:0)

谢谢大家的答案。花点时间回到这里,但我有一个适合我的解决方案。在粘贴代码解决方案之前,我将再解释一下自己。案例是我需要一个接受params的函数,但是我想在时间上使用它。例如,如果你有javascript函数接受像'input type = file'这样的html元素,你希望在这个html元素上的change事件将它传递给这个函数。我希望这个例子足够清楚。这是我正在寻找的代码的一个简单例子:

var Scripts = function(){
  var _example =function(params){
    code.....
  };
  return {
     init:function(){
      ...call some other functions.....
     },
     example:_example 
  }

}();
jQuery(document).ready(function(){
  Scripts.init();
})



Scripts.example(params);...call function like this in tour code...