简体   繁体   English

在Javascript中定义和调用函数的最佳方法

[英]Best way to define and call functions in Javascript

Below is just some sample Javascript that I posted that shows 2 different ways that javascript functions are being defined and called. 下面是我发布的一些示例Javascript,它显示了定义和调用javascript函数的两种不同方式。

Is there a name for these different methods? 这些不同的方法有名称吗?

Which method is preferred? 哪种方法更受青睐?

The first code block looks really simple, pretty much the same as a procedural PHP function is defined and called. 第一个代码块看起来非常简单,几乎与定义和调用的过程PHP函数相同。

The second I realize is set up more like a class/namespace it just get's a little confusing for me as I have not studied javascript too much yet. 第二个我意识到设置更像一个类/命名空间它只是让我有点困惑,因为我还没有研究过多的javascript。 Am I correct in my thinking that all these functions could be coded in either method as the first or second code blocks and still work? 我是否认为所有这些函数都可以在任何一种方法中编码为第一个或第二个代码块并且仍然有用?

Sorry if my question is not clear enough, I will revise if needed, thanks for the help/info 对不起,如果我的问题不够明确,我会在需要时进行修改,感谢您的帮助/信息

initCommentsHelp();

function initCommentsHelp() {
    $('#view-comments-help-a').live('click', function() {
      $('#comments-help').slideToggle("normal");
      return false;
    });
}

VS doing this VS这样做

Screenshot.Like.Shot.toggle();
Screenshot.Comment.toggle();
Screenshot.Flag.flag();
Screenshot.Flag.unflag();

var Screenshot = {
    Like: {
        Shot: {
            toggle: function() {
                if ($('.fav a.fav-toggle.processing').length == 0) {
                    $.ajax({
                        type: 'POST',
                        url: url,
                        data: data,
                        beforeSend: function() {
                            $('.fav-toggle').addClass('processing');
                            $link.text('Wait...');
                        },
                        success: function(responseHtml) {
                            $('#like-section').replaceWith(responseHtml);
                        }
                    });
                }

                return false;
            }
        },
    Comment: {
                toggle: function() {
                    var link = $(this);
                    var data = link.hasClass('liked-by-current-user') ? {_method: 'delete'} : null;
                    $.ajax({
                        type: 'POST',
                        url: this.href,
                        data: data,
                        success: function(responseHtml) {
                            link.closest('.comment').replaceWith(responseHtml);
                        }
                    });

                    return false;
            }
        }
    },
    Flag: {
        // Flag a screenshot as inappropriate or Appropriate
        flag: function(){
            var link = $(this);
            var screenshotId = link.modelId();
            if(!confirm("Are you sure you want to flag this shot?"))
                return false;

            $.ajax({
                type: 'POST',
                url: this.href,
                data: {
                    screenshot_id: screenshotId
                },
                success: function(responseHtml) {
                    $('#flag-section').html(responseHtml);
                }
            });

            return false;
        },
        unflag: function() {
            var link = $(this);
            var screenshotId = link.modelId();
            $.ajax({
                type: 'POST',
                url: this.href,
                data: {
                    _method: 'delete',
                    screenshot_id: screenshotId
                },
                success: function(responseHtml) {
                    $('#flag-section').html(responseHtml);
                }
            });

            return false;
        }
    },
};

The first way is generally preferred for writing standalone functions. 第一种方法通常优选用于编写独立功能。 You can write them as 你可以把它们写成

function testFunction() {
  // your code here...
}

or 要么

var testFunction = function() {
  // your code here...
}

The second example you have posted is used for namespacing your objects. 您发布的第二个示例用于命名空间对象。 You can read more about namespacing in this article : Namespacing in JavaScript 您可以在本文中阅读有关命名空间的更多信息: JavaScript中的命名空间

A function that's an object property (called via an object reference, eg obj.func() ) is what's called a "method". 作为对象属性的函数(通过对象引用调用,例如obj.func() )就是所谓的“方法”。 A function not associated with an object is called a "free function". 与对象无关的函数称为“自由函数”。 Methods have special access privileges not afforded to free functions. 方法具有不提供给自由函数的特殊访问权限。 Exactly what those privileges are depends on the language, but all OO languages include a special variable (you can consider it a hidden parameter) available within the function body to access the object the method is bound to. 这些权限究竟取决于语言,但所有OO语言都包含一个特殊变量(您可以将其视为隐藏参数),可在函数体中访问该方法所绑定的对象。 In JS, the name of this parameter is this . 在JS中,此参数的名称是this

this exists in free functions, where it refers to the global object. this存在于自由函数中,它引用全局对象。 You can think of free functions and global variables as being properties of a global, default object. 您可以将自由函数和全局变量视为全局默认对象的属性。 For browsers, the global object is window . 对于浏览器,全局对象是window Free functions, then, are similar to global variables, which are generally bad . 因此,自由函数类似于全局变量,通常是坏的 Free functions don't as often cause problems as global variables, but they still can, and for the same reasons. 自由函数不会像全局变量那样经常导致问题,但它们仍然可以,并且出于同样的原因。 As a result, some developers use objects as namespaces to prevent name collisions. 因此,一些开发人员使用对象作为名称空间来防止名称冲突。

For example, one module might create a sign function that returns whether a number is positive, negative or 0. Another module might have a sign function that digitally signs a message. 例如,一个模块可能会创建一个sign函数,该函数返回一个数字是正数,负数还是0.另一个模块可能有一个数字签名消息的sign函数。 These modules are created by different companies, each unaware of the other. 这些模块由不同的公司创建,每个公司都不知道另一个。 Imagine a developer wants to use both modules. 想象一下,开发人员想要使用这两个模块。 If both were defined as free functions, whichever were defined second would replace the first, wreaking havoc in the other module. 如果两者都被定义为自由函数,则以第二个定义的第二个将替换第一个,在另一个模块中造成严重破坏。 To prevent this, each function can be defined as properties of separate objects. 为了防止这种情况,可以将每个函数定义为单独对象的属性。

The actual difference between free functions and methods is in how they are accessed. 自由函数和方法之间的实际区别在于如何访问它们。 Methods are accessed as a property of an object, while free functions are accessed directly by name or as a variable. 方法作为对象的属性进行访问,而自由函数可以通过名称或变量直接访问。 Note that the same function can be treated as a method or free function, depending on how you access it. 请注意,根据您访问它的方式,可以将相同的函数视为方法或自由函数。

var obj = {
    type: 'method',
    meth: function (){
        return this.type;
    }
};
var func = obj.meth,
    name = 'free';

// the following two lines call the same function, though `this` will be bound differently for each.
obj.meth(); // returns 'method'
func();     // returns 'free'

You can even take a free function and call it as a method in a number of ways: 您甚至可以使用自由函数并以多种方式将其作为方法调用:

function func(a, b) {
    return this.foo+a+b;
}
var obj = {foo: 'bar'};
// call func as a method using the `call` method
func.call(obj, 'baz', 'bam');
// call func as a method using the `apply` method
func.apply(obj, ['baz', 'bam']);

// call func as a method in the usual way
obj.meth = func;
obj.meth(1, 2); // 'foo12'

If you look more closely at your second sample, you'll note that most of the methods use the this variable. 如果你仔细观察你的第二个样本,你会注意到大多数方法都使用this变量。 These must remain methods; 这些必须保留方法; making them free functions will likely cause bugs. 使它们成为自由函数可能会导致错误。

One is defining the functions in an object and the other is just defining a function by itself. 一个是定义对象中的函数,另一个是仅定义函数。 Functions are first class objects in JavaScript so they don't need an object to be defined. 函数是JavaScript中的第一类对象,因此它们不需要定义对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM