尝试理解 JavaScript 中的对象和方法创建
Trying to understand object and method creation in javascript
我试图理解在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);
我难以理解以下内容:
为什么作者更喜欢用
(function(){...}).call(this);
包裹所有东西?也许是为了避免创建全局变量?剧本最后的
.call(this)
部分有什么用?作者为什么要创建
root
变量,以下几行有什么用?root = typeof exports !== "undefined" && exports !== null ? exports : window; root.Instafeed = Instafeed;
由于这是在 coffeescript 中创建对象和方法的首选方法,我想这是更好的方法之一。但是它相对于以下版本的优势让我无法理解:
function Instafeed(params) {
...
}
Instafeed.prototype.run = function() {
...
}
-
是的;这使得所有以前的顶级
var
都变成了局部变量。 -
它使
this
等于函数内的全局对象
它 允许它作为CommonJS模块(用于Node.js或Browserify)工作。
相关文章:
- 从 javascript 中的对象方法返回一个对象
- 在Javascript中调用对象方法时不是函数类型错误
- Java Script将对象方法映射到数组中的对象
- 将数据从promise then方法传递到对象方法
- 设置显示后Flash对象方法不可用:无
- 通过引用Javascript中的另一个函数来传递对象方法
- Javascript库对象方法声明
- JavaScript对象范围-在对象方法中使用对象变量
- jQuery:如何使用文字对象方法中的方法来获取全局变量
- Javascript 对象方法不更新变量
- setInterval 只在对象方法上运行一次
- 对象方法中函数中的上下文
- 用JavaScript编写对象方法的最佳方式是什么
- 使用回调处理程序调用函数内部的父对象方法
- 从Javascript中的对象方法中访问全局变量
- 将此(对象)传递到一个对象方法嵌套方法中
- 为什么我得到“;不是函数错误”;对于我的对象方法
- 带有回调的Javascript对象方法中的递归
- 更正Node.js异步管道中的对象方法调用
- 如何在对象方法上调用requestAnimFrame