basic javascript syntax question - javascript

What does the following javascript code mean? I guess it's defining a function within a function to make it look like OOP? Why the function can return multiple functions? what is the bracket at the end?
var grid_ui = function () {
function setup_data_source() {}
return {
init: function () {},
set_ds: function(rpt_headers, rpt_rows) {}
} // return
}();

The { } notation is called an object literal. It is same as:
a = new Object();
a.init = function() { };
a.set_ds = function(...) { };
return a;
and return { } returns an object.
The function () { ... }(); is a self-invoking function: it creates an anonymous function them immidiately invokes it.
In your code, the self-invoking function returns an object of functions, which is a namespace pattern. The value of grid_ui now contains { init: ..., set_ds: ... }, which is mentioned in return.
These concepts are very difficult to explain in one SO answer, so I will provide you some links:
http://www.hunlock.com/blogs/Functional_Javascript/
http://www.dustindiaz.com/namespace-your-javascript/

it is defining an function then calling it and taking the return value and assigning it to grid_ui.
the value of grid_ui is now the object (also called a dictionary) containing the keys init and set_ds.
In javascript, you can define functions within functions and assign functions to variables.
Now you can make calls like grid_ui.init() and grid_ui.set_ds("test", 1).

It is OOP. Functions are objects in JavaScript.
This code means that there is a variable, grid_ui, which evaluates to an object that has two "public" functions, init and set_ds. init and set_ds also have a context which includes a "private" function, setup_data_source.
There are no brackets.

Related

How to call a method in an object

I am having trouble calling the object method,it always throw a error this.b
is not a function
var a={
b:()=>"3333",
c:()=>this.b();
}
console.log(a.c());
Your code does not work because the arrow function binds the function to the scope in which it is defined. In this case, you are in the global scope when you create the function "c" using the arrow function. Often this can be fixed with a bind call. However, in this case, I would just convert to a classical function. This is a good lesson in why you should not be lazy and use the arrow function to save a few characters. The arrow function IS NOT the same as a normal function and can lead to hard to debug bugs.
var a={
b:()=>"3333",
c:function () { return this.b() }
}
console.log(a.c())
Simplest way to make your code working is to use a instead of this
var a = {
b: () => "3333",
c: () => a.b()
};
console.log(a.c());
Basically, the reference of c, will call the value based on lexical scope, the same of 'window.c()'.
To fix your implementation, do:
var a={
b:()=>{ return "333"; },
c:function(){ return this.b(); }
}
console.log(a.c()); // Here we have a "333"
Why this happens?
The function expressions work about dynamic scope, different of Arrow Functions. To access Object Properties and reference to same this, use { yourProperty: function() { return "Hello, World"; } }

Difference between object and returning object from IIFE

Using this keyword inside functions of an object works, but refering to other functions without this doesn't. When I put out those functions before the object, both ways work. Why is that so?
var Obj = {
func1: function () {
console.log(this.func2()); // works
console.log(func2()); // doesn't work
},
func2: function () {
return 5;
}
};
Obj.func1();
But doing the same in IIFE:
var Obj = (function () {
function func1() {
console.log(this.func2()); // works
console.log(func2()); // works
}
function func2() {
return 5;
}
return {
func1: func1,
func2: func2
};
})();
Obj.func1();
This has nothing to do with the IIFE, in the first example you have an object literal, in the second regular functions.
Of course, object literals would need the name of the object (or this if the this-value is the object, like inside an object literal) followed by the property to access it, while named functions can be accessed anywhere in that scope by just using the name.
var obj = {
prop : function() {...}
}
prop(); // fail ... undefined
obj.prop(); // works
// then _______________________________________________________________
function prop() {...}
prop(); // works fine
This is really what you're doing, you've just wrapped it up in different objects and immediately invoked function expressions, so it looks somewhat the same, but it's not.
There is no difference.
In both cases, you're working with an object. So, you need to use this or the object name to call the function defined under an object.

Difference between two JavaScript object types

I see objects in JavaScript organized most commonly in the below two fashions. Could someone please explain the difference and the benefits between the two? Are there cases where one is more appropriate to the other?
Really appreciate any clarification. Thanks a lot!
First:
var SomeObject;
SomeObject = (function() {
function SomeObject() {}
SomeObject.prototype.doSomething: function() {
},
SomeObject.prototype.doSomethingElse: function() {
}
})();
Second:
SomeObject = function() {
SomeObject.prototype.doSomething: function() {
},
SomeObject.prototype.doSomethingElse: function() {
}
}
Both of those examples are incorrect. I think you meant:
First:
var SomeObject;
SomeObject = (function() {
function SomeObject() {
}
SomeObject.prototype.doSomething = function() {
};
SomeObject.prototype.doSomethingElse = function() {
};
return SomeObject;
})();
(Note the return at the end of the anonymous function, the use of = rather than :, and the semicolons to complete the function assignments.)
Or possibly you meant:
function SomeObject() {
}
SomeObject.prototype.doSomething = function() {
};
SomeObject.prototype.doSomethingElse = function() {
};
(No anonymous enclosing function.)
Second:
function SomeObject() {
}
SomeObject.prototype = {
doSomething: function() {
},
doSomethingElse: function() {
}
};
(Note that the assignment to the prototype is outside the SomeObject function; here, we use : because we're inside an object initializer. And again we have the ; at the end to complete the assignment statement.)
If I'm correct, there's very little difference between them. Both of them create a SomeObject constructor function and add anonymous functions to its prototype. The second version replaces the SomeObject constructor function's prototype with a completely new object (which I do not recommend), where the first one just augments the prototype that the SomeObject constructor function already has.
A more useful form is this:
var SomeObject;
SomeObject = (function() {
function SomeObject() {
}
SomeObject.prototype.doSomething = doSomething;
function doSomething() {
}
SomeObject.prototype.doSomethingElse = doSomethingElse;
function doSomethingElse()
}
return SomeObject;
})();
There, the functions we assign to doSomething and doSomethingElse have names, which is useful when you're walking through code in a debugger (they're shown in call stacks, lists of breakpoints, etc.). The anonymous function wrapping everything is there so that the doSomething and doSomethingElse names don't pollute the enclosing namespace. More: Anonymouses anonymous
Some of us take it further:
var SomeObject;
SomeObject = (function() {
var p = SomeObject.prototype;
function SomeObject() {
}
p.doSomething = SomeObject$doSomething;
function SomeObject$doSomething() {
}
p.doSomethingElse = SomeObject$doSomethingElse;
function SomeObject$doSomethingElse()
}
return SomeObject;
})();
...so that not only do we see doSomething, but SomeObject$doSomething in the lists. Sometimes that can get in the way, though, it's a style choice. (Also note I used the anonymous function to enclose an alias for SomeObject.prototype, to make for less typing.)
First off, both snippets will not parse for me (Chrome) - you should use = in place of :. That said, my humble opinion follows.
The latter snippet is slightly strange, because you actually define methods on SomeObject's prototype at the time of the object construction, rather than at the parse time. Thus, if you have re-defined some method on SomeObject.prototype, it will get reverted to the original version once a new object is constructed. This may result in unexpected behavior for existing objects of this type.
The former one looks fine, except that the (function { ...} ())() wrapper may not be necessary. You can declare just:
function SomeObject() {}
SomeObject.prototype.doSomething = function() {}
SomeObject.prototype.doSomethingElse = function() {}
The actual difference between first and second in your questions is just:
var o = (function () {})(); # call this (A)
and
var o = function () {}; # call this (B)
Unfortunately, neither of the examples that you gave are written correctly and, while I don't think either will actually give an error at parse-time, both will break in interesting ways when you try to do things with the result.
To give you an answer about the difference between (A) and (B), (A) is the immediate function application pattern. The JavaScript Patterns book has a good discussion, which I recommend.
The actual problems in your code have been explained by other people while I was writing this. In particular T.J. Crowder points out important things.

jQuery-style function that can be accessed like an object

I am creating an AJAX API for a web service and I want to be able to call jQuery-like accessors.
jQuery seems to be able to execute 'jQuery' as a function, but also use it to directly access the object that is the result of the function EG:
jQuery();
jQuery.each({});
This is the trick that I can't seem to pull off:
myAPI('foo'); //output: 'foo'
myAPI('foo').changeBar(); //output: 'foo' 1
myAPI.changeBar(); //Error: not a function
I have seen the answers to similar questions, which are helpful, but don't really answer my question.
#8734115 - Really interesting, but you can't access the methods that were set by f.prototype.
#2953314 - Uses Multiple operations to create object instead of a single function.
here is my code:
(function(window) {
var h = function(foo) {
// The h object is actually just the init constructor 'enhanced'
return new h.fn.init(foo);
};
/**
* Methods defined at protoype.
*/
h.fn = h.prototype = {
constructor: h,
init: function(foo) {
console.log(foo);
return this;
},
splice : function () {},
length : 0,
bar : 0,
changeBar : function() {
this.bar++;
return this.bar;
}
};
h.fn.init.prototype = h.fn;
//Publish
window.myAPI =h;
}( window));
I'm sure I'm missing something simple :(
What jQuery is doing there is using jQuery as both a function and as a pseudo-namespace. That is, you can call jQuery: var divs = jQuery("div"); and you can use properties on it, e.g.: jQuery.each(...);.
This is possible because in JavaScript, functions are first-class objects, and so you can add arbitrary properties to them:
function foo() {
alert("Foo!");
}
foo.bar = function() {
alert("Bar!");
};
foo(); // "Foo!"
foo.bar(); // "Bar!"
That's literally all there is to it.
Within the call to bar, this will be the foo function (because this is determined entirely by how a function is called, not where it's defined). jQuery doesn't use this to refer to itself (usually it uses this to refer to DOM elements, sometimes to other things like array elements; when referring to itself, since it's a single thing, it just uses jQuery).
Now, you might want to ensure that your functions have proper names (whereas the function I assigned to bar above is anonymous — the property has a name, but the function does not). In that case, you might get into the module pattern:
var foo = (function() {
function foo() {
alert("Foo!");
}
function foo_bar() {
alert("Bar!");
}
foo.bar = foo_bar;
return foo;
})();
foo(); // "Foo!"
foo.bar(); // "Bar!"
That pattern also has the advantage that you can have private data and functions held within the scoping function (the big anonymous function that wraps everything else) that only your code can use.
var foo = (function() {
function foo() {
reallyPrivate("Foo!");
}
function foo_bar() {
reallyPrivate("Bar!");
}
function reallyPrivate(msg) {
alert(msg);
}
foo.bar = foo_bar;
return foo;
})();
foo(); // "Foo!"
foo.bar(); // "Bar!"
reallyPrivate("Hi"); // Error, `reallyPrivate` is undefined outside of the scoping function
In your code, you're assigning things to the prototype property of the function. That only comes into play when the function is called as a constructor function (e.g., via new). When you do that, the object created by new receives the function's prototype property as its underlying prototype. But that's a completely different thing, unrelated to what jQuery does where it's both a function and a pseudo-namespace.
You do not need any of that weirdness, to use stuff like $.each
you just attach functions to the function object instead
of the prototype object:
function Constructor() {
if (!(this instanceof Constructor)) {
return new Constructor();
}
}
Constructor.prototype = {
each: function() {
return "instance method";
}
};
Constructor.each = function() {
return "static method";
};
var a = Constructor();
a.each(); //"instance method"
Constructor.each(); //"static method"

When to use anonymous JavaScript functions?

I'm trying to understand when to use anonymous JavaScript functions.
State differences between the functions? Explain when you would use each.
var test1 = function(){
$("<div />").html("test1").appendTo(body)
};
function test2() {
$("<div />").html("test2").appendTo(body)
}
I think the answer is that one uses anonymous function and the other doesn't to replace an empty div element. Does that seem right?
In your example it really doesn't make a huge difference. The only difference is that functions declared using function foo() { } are accessible anywhere within the same scope at any time, while functions declared using var foo = function () { } are only accessible after the code that does the assignment has run.
foo(); // ok
function foo() { ... };
bar(); // error, bar is not a function
var bar = function () { ... };
bar(); // ok
You usually use anonymous functions in cases where you don't need a named function, or where you're constructing objects:
arr.sort(function (a, b) { return a - b; }); // anonymous callback function
function MyObject() {
this.foo = function () { ... } // object constructor
}
You would use a function like the following (which is another type of anonymous function) when you do not want to pollute the global namespace:
(function() {
var pollution = 'blablabla';
function stinky() {
// Some code
}
})();
You may check John Resig's Secrets of JavaScript Libraries, especially page 47 for JavaScript function. Quite lengthy, but you'll learn more about JavaScript

Categories

Resources