如何定义应用程序的方法

How to define methods for an application

本文关键字:应用程序 方法 定义 何定义      更新时间:2023-09-26
这与

我今天提出的另外两个问题类似,但我仍在尝试了解如何在JavaScript中正确分配变量。

我的代码的输出是这样的:

x: 3
x: undefined // I was expecting 3 here

这是我的代码:

var myApplication = {};
(function() {
    function beep(x) {
        console.log('x: ' + x);
        var closure = {};
        return function() {
            console.log('return function() {');
            if (arguments.length) {
                console.log('setter: ' + x);
                closure.result = x;
            } else {
                console.log('getter: ' + closure.result);
                return closure.result;
            }
        }
    }
    myApplication.beep = beep;
})();
myApplication.beep(3);
RESULT = myApplication.beep();

我认为问题出在哪里我说:myApplication.beep = beep;我认为我必须通过原型或其他方式分配它。

首先,函数在javascript中是一等公民。

所以当你这样做时

return function() {
   console.log('return function() {');
   if (arguments.length) {
      console.log('setter: ' + x);
      closure.result = x;
   } else {
      console.log('getter: ' + closure.result);
      return closure.result;
   }
}

此函数不执行,您仅作为 beep 函数的值返回。

因此,在我们的例子中,唯一真正执行的代码是:

var myApplication = {};
(function() {
    function beep(x) {
        console.log('x: ' + x);
    }
    myApplication.beep = beep;
})();
myApplication.beep(3);
RESULT = myApplication.beep();

在这种情况下,您只记录传递给beep的第一个参数,因此3然后undefined

现在对于你想在这里做的事情,不需要使用闭包或原型:

var myApplication = {
  x : null,
  beep : function (x) {
    if (typeof x != 'undefined') {
      this.x = x;
    } else {
      return this.x;
    }
  }
};
// set x
myApplication.beep(3);
// get x
var x = myApplication.beep();
console.log('x :', x);

我会避免过早地弄乱关闭。

当你第一次调用 beep(3( 时,它会返回一个函数 - 但你实际上并没有用这个函数做任何事情。我想你可能在倒数第二行是这个意思?...:

myApplication.beep = myApplication.beep(3);

事实上,我认为第二次调用哔哔声只是返回另一个函数,但其"x"参数设置为 undefined。

另外:为了节省一些代码编写,而不是声明然后分配"哔哔",你可以这样写:

myApplication.beep = function(x) { ...

或者,可以从一开始就立即声明整个对象:

myApplication = {
  beep: function(x) {
  },
  otherFn: function(y) {
  }
}
相关文章: