1

所以我试图找出声明函数的不同方法......以及低内存使用的最佳方法是什么......

我一直在做的方式是方法#4,我猜它是ATROCIOUS。我基本上做了一堆不同的“ function XYZ(){ //stuff }”,并一直调用它来执行操作......或多或少是一种管理所有代码并组织它的方式......不是因为性能、内存或任何技术相关的原因...... . 任何人都可以请解释一下哪种方法最好吗?(或者如果您有自己的方法,请发布)为什么?

//method 1
var sayHey = new Object();
    sayHey.derp = 'derp';
    sayHey.herp = function(){
        alert('herp');
    };

//side question: would this.derp = 'derp' be the same as sayHey.derp? if so, would it be better to use this rather than sayHey?


//method 2
var sayHey2 = function() {
    return {
        derp : 'derp',
        herp : function(){
            alert('herp');
        }
    }
}();

//method 3
var sayHey3 = {
    derp: 'derp',
    herp: function(){
        alert('herp');
    }
};

//method 4
var derp = 'derp';
function herp(){
    alert('herp');
}
4

1 回答 1

1
  • 方法 1 和 3相同。只是创建对象的不同方式。

  • 附带问题: this.derp如果"derp"您直接从对象调用方法。换句话说,如果你这样做this.herp(),那么thisherp()函数中将是你的 sayHey对象。

  • 方法 2也是相同的,只是有一个不必要的函数调用,它没有特别使用创建的变量范围。您可以derp在函数内部创建一个局部变量而不是对象上的属性,以便只能通过herp()方法访问它。这为变量提供了一些保护。

  • 方法 4正在创建一个本地函数,因此您不会直接在对象上获取它。每个都有不同的用例。

于 2013-03-08T19:16:33.863 回答