我曾经知道这意味着什么,但我现在正在努力...
这基本上是说document.onload吗?
(function () {
})();
Run Code Online (Sandbox Code Playgroud) 伙计们可以在Javascript中使用任何一个解释上下文call和apply方法吗?
为什么要使用call而apply不是直接调用函数?
在John Resig的书"Pro Javascript技术"中,他描述了一种使用以下代码生成动态对象方法的方法:
// Create a new user object that accepts an object of properties
function User(properties) {
// Iterate through the properties of the object, and make sure
// that it's properly scoped (as discussed previously)
for (var i in properties) {
(function() {
// Create a new getter for the property
this["get" + i] = function() {
return properties[i];
};
// Create a new setter for the property
this["set" + i] = function(val) {
properties[i] = val;
}; …Run Code Online (Sandbox Code Playgroud) IIFE需要访问非重写window对象 - 可以看作:
像(jQuery示例):
$(function (global) {
// do something with global
})( window );
Run Code Online (Sandbox Code Playgroud)
但有时我也看到这个(underscore.js):
(function() {
var global= this;
// do something with global
}).call(this);
Run Code Online (Sandbox Code Playgroud)
问题1:有什么区别吗?如果是这样,我应该何时使用?
问题2:this里面IIFE 是 window.为什么有必要"发送" window/ call(this)?(jQuery没有使用严格模式imho)
NB
看起来jQuery(从1.11.0开始)也采用了这种模式:
(function (global, factory)
{
//....
}(typeof window !== "undefined" ? window : this, function (window, noGlobal)
{
//...
});
Run Code Online (Sandbox Code Playgroud) 下面是我的代码片段.我得到的错误是,当我执行搜索并调用该方法时_searchData,它成功调用该方法_lookUpSuccess,但然后返回以下错误:
JavaScript运行时错误:无法获取未定义或空引用的属性"_displayResult"
当它试图调用该_displayResult方法时.
为什么会这样?
(function () {
// make this an object property/method eventually
var displayResult = function (queryResult) {
for (var i = 0; i < holder.length; i++) {
//document.querySelector(".item-content .title").textContent = "FilmApp";
document.querySelector(holder[i]).textContent = queryResult[i];
}};
// Creates a new page control with members
ui.Pages.define(searchPageURI, {
//...
_searchData: function (queryText) {
searchBase = 'http://www.example.com/web-service2.php?termID=';
searchFormat = 'JSON';
searchFormatPiece = '&format=' + searchFormat;
if (!window.Data) {
var searchUrl = searchBase + queryText + …Run Code Online (Sandbox Code Playgroud)