尝试理解 JavaScript 中的对象和方法创建

Trying to understand object and method creation in javascript

本文关键字:对象 方法 创建 JavaScript      更新时间:2023-09-26

我试图理解在javascript中创建对象和方法的不同方法。我读过很多文章,博客和堆栈溢出问题,我想我大致了解这个概念。但是我遇到了一个小的javascript库(用coffeescript编写),它创建对象和方法的方式让我有点困惑。

我包含一个片段,但如果你愿意,你可以在instafeed.js找到完整的脚本。

法典:

(function() {
    var Instafeed, root;
    Instafeed = (function() {
        function Instafeed(params) {
            var option, value;
            this.options = {
                target: 'instafeed',
                get: 'popular',
                resolution: 'thumbnail',
                sortBy: 'most-recent',
                links: true,
                limit: 15,
                mock: false
            };
            if (typeof params === 'object') {
                for (option in params) {
                  value = params[option];
                  this.options[option] = value;
                }
            }
        }
        Instafeed.prototype.run = function() {
            var header, instanceName, script;
            if (typeof this.options.clientId !== 'string') {
                if (typeof this.options.accessToken !== 'string') {
                  throw new Error("Missing clientId or accessToken.");
                }
            }
            if (typeof this.options.accessToken !== 'string') {
                if (typeof this.options.clientId !== 'string') {
                  throw new Error("Missing clientId or accessToken.");
                }
            }
            if ((this.options.before != null) && typeof this.options.before === 'function') {
                this.options.before.call(this);
            }
            if (typeof document !== "undefined" && document !== null) {
                script = document.createElement('script');
                script.id = 'instafeed-fetcher';
                script.src = this._buildUrl();
                header = document.getElementsByTagName('head');
                header[0].appendChild(script);
                instanceName = "instafeedCache" + this.unique;
                window[instanceName] = new Instafeed(this.options);
                window[instanceName].unique = this.unique;
            }
            return true;
        }
    ...
        return Instafeed;
    })();
    root = typeof exports !== "undefined" && exports !== null ? exports : window;
    root.Instafeed = Instafeed;
}).call(this);

我难以理解以下内容:

  1. 为什么作者更喜欢用(function(){...}).call(this);包裹所有东西?也许是为了避免创建全局变量?

  2. 剧本最后的.call(this)部分有什么用?

  3. 作者为什么要创建root变量,以下几行有什么用?

    root = typeof exports !== "undefined" && exports !== null ? exports : window;
    root.Instafeed = Instafeed;
    

由于这是在 coffeescript 中创建对象和方法的首选方法,我想这是更好的方法之一。但是它相对于以下版本的优势让我无法理解:

function Instafeed(params) {
    ...
}
Instafeed.prototype.run = function() {
    ...
}
  1. 是的;这使得所有以前的顶级var都变成了局部变量。

  2. 它使this等于函数内的全局对象

  3. 允许它作为CommonJS模块(用于Node.js或Browserify)工作。