对象的属性VS调用函数

Property of an Object VS Calling function

本文关键字:调用 函数 VS 属性 对象      更新时间:2023-09-26

所以我想找出不同的方法来声明函数…什么是降低内存使用的最佳方法…

我一直在做的方法是方法#4,我猜这是很糟糕的。我基本上制作了一堆不同的"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');
}
  • 方法1与方法3相同。只是创建对象的不同方式。

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

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

  • 方法4是一个局部函数,所以你不能直接在你的对象上得到它。