declare function name in object, Why? [duplicate] - javascript

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 7 years ago.
Was working on some js code performance and saw this approach:
window.sample = {
foo: function foo(a,b){
// code goes here
}
bar: function bar(a,b){
// code goes here
}
}
is there any reason why you would decelerate the function name after the word "function" ?
dose it help to debug?
is it good or bad or just unnecessary?

The only reason would be that you can use the function itself from within the function without a reference to the object:
foo: function foo(a,b){
return a > 0 ? a + foo(a-1,b) : b;
}
Note howeever that support for named function literals is not consistent across browsers, so you should really avoid using it.

instead of assigning an anonymous function to the foo and bar properties, they are assigning named functions.
it can be helpful for debugging: the only difference this makes, that i know of, is that you will see the names of the functions show up in the call stack instead of "javascript anonymous function"

It's a named function expression. The name of the function is only available as a variable within the function itself. This can be useful for recursion, for example:
var obj = {
foo: function foo(node) {
// Do something to node
var childNode = node.firstChild;
while (childNode) {
foo(childNode);
childNode = childNode.nextSibling;
}
}
};
The name of the function is also available in most browsers via the non-standard name property of the function, which can help identify functions while debugging or examining stack traces.
IE < 9 has a flawed implementation, so you need to exercise care when using it. Full details can be found in Juriy Zaytsev's excellent article on the subject.

Related

how is jQuery able to call an object $ [duplicate]

This question already has answers here:
How does jQuery makes the jQuery object both a function and an object property?
(3 answers)
Closed 7 years ago.
If $ is an object then how is jQuery able to call it with parenthesis (), like $('#MYdIV'). That is my first and most important question.
I am trying to learn design patterns, and underlaying mechanisms of creating an object. So I want to make library that when user type myLibrary({option1:true}); he would be able to instantiate an object without using keyword new.Just like jquery and this: https://github.com/bendc/animateplus/blob/master/animate.js
In this example he is not using keyword new nor this. He is just creating IIFE animate which returns another function with the same name. I don't know how is he able to do that. Is animate bound to global object?
jQuery or $ is just a function. Consider the following example which produces an object with the similar behavior.
Of course, jQuery has the much more complex and smart structure, this is just an example:
var not$ = function(o) {
var result = document.querySelectorAll(o);
result.customInnerText = function(text) {
if (text === undefined) {
return document.querySelector(o).innerText;
} else {
document.querySelector(o).innerText = text;
}
};
result.customClickHandler = function(callback) {
document.querySelector(o).addEventListener('click', callback);
};
return result;
};
not$.customConsoleLog = function(text) {
console.log(text);
};
not$("a").customClickHandler(function() {
var exampleText = not$("#title").customInnerText();
not$("#text").customInnerText(exampleText + "It works!");
not$.customConsoleLog(not$("p").length);
not$.customConsoleLog(not$("p")[0]);
});
Click me!
<p id="title">Example:</p>
<p id="text">Check!</p>
First a few terms:
a primitive is one of the following: string, number, boolean, null, undefined, symbol
An object is essentially any kind of thing that's not a primitve in Javascript. If it's a thing you want to use or manipulate, it's an object.
A function is a particular type of object that can be used to run javascript. This can be called by using the syntax function()
A constructor is just a function. It's a function which is intended to be called with the new keyword, as in new Thing(). Note the capital letter - that's convention.
So we can see that JQuery uses a function, not a constructor function. Specifically, if you look into the source code we'll find something like $ = function() {...}
And that's basically it - they define a global variable called $ and define it to be a function that can be used. Of course, since functions are objects, you can also do things like $.randomNumber = 4 without problems, and it won't affect JQuery in the slightest.
So if you're wanting to do something similar, you'll want to define your own global variable and set it as a function - just be aware of what's already taken - i.e. don't use $ or _ or whatever.
(1) $ is not an object, but a function.
console.log(typeof $);
// function
What might be confusing here - and this is just a guess - is that you can access properties on the $ variable, e.g. $.extend or $.fn (used when writing your own jQuery plugins). This is normal, as functions can have properties themselves. The ECMAScript specifications allow that.
(2) Constructor functions can be used to create new objects, but are not required. You can just used object literals, and that works just as well. As pointed out by #Jeff in the other answer, a function invoked with new makes it a constructor function. Otherwise, there is no difference in the syntax. It is up to you to pick whether you wish to use.

Javascript: Is the "this" useful or necessary in the case? [duplicate]

This question already has answers here:
What does "this" mean in jQuery? [duplicate]
(6 answers)
Closed 7 years ago.
Reviewing some legacy code and saw it. The function body was done in pure Javascript without using any 3rd party library.
Could anyone shed a light on the use of "this" in (function() { })(this)?
Full codes:
(function() {
var root = this;
var SOMEVAR;
SOMEVAR = root.SOMEVAR = {};
SOMEVAR.windowOffset = 0;
SOMEVAR.defaultBase = 195;
SOMEVAR.resizeIFrame = function(){
// some codes
};
SOMEVAR.resetIFrameSize = function(height) {
// some codes
}
window.SOMEVAR = SOMEVAR;
})(this);
I actually read all "this" related usages before I asked the question. I just couldn't find this usage fits in those I read. And somehow, I don't think the "this" here is not even necessary because all the codes want is to create the "SOMEVAR" and bind it to "window". Am I correct?
Thanks
This is a somewhat weird example of an Immediately-Invoked Function Expression (IIFE). The first part:
(function(){})
simply defines a function (the outer parentheses are unnecessary). This function is then called, passing this as an argument. Usually one would actually declare a parameter and then do something to the parameter inside the function:
(function(context) {
// do something to or with context
})(this);
What object is actually referenced by this depends on where this code is executing and whether strict mode is in effect. See the docs for this for more information.
You're defining an anonymous function and then immediately invoking it with the this parameter.
If you're just looking to understand the meaning of this, then refer to this other question.
Ah, what is this. The oldest question in the javascript book. Generally speaking, this refers to the context that the current code is being executed in. If you have "top level" code being run straight in a script tag, it refers to window. In a click event? The current element. In a constructor? The object that will be constructed. You can even make it whatever you want with call and apply.
If you see this construct:
(function(ns) { })(this);
not inside other function then this is a reference of default namespace of script execution. In browsers that default namespace has quite strange name window therefore the following will output true:
(function(ns) {
console.log( ns === window );
})(this);
Such ns (namespace) variable is useful when you need for example check variable existence in namespace. This, for example:
alert(foo);
will rise an error "undefined variable foo", but this:
(function(ns) {
alert(ns.foo);
})(this);
will show alert with the word "undefined".
Another usage is in modules that can work as inside browser as in node.js and the like. Node.js has no notion of window so that construct above is the only reliable way to get reference to default namespace/scope object.

Functions Declarations [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
What is the right way to declare Javascript Function?
From codeacademy.com i got this way:
var someFunction = function(paramA, paramB){
// do some function here
}
But because my basic of programming is PHP, i prefer declare function with this way:
function someFunction(paramA, paramB){
// do some function
}
What I'm concern is which one is recommended way to declare function, I'm afraid if my preferred way have some consequences, but i love that way so much because it make my NetBeans Code Navigator can read all of my functions.
Both are acceptable. Indeed, you can also do:
foo = function bar() {
console.log(arguments.callee.name);
};
If you then call foo(), you'll see "bar" in the console.
The first method creates an anonymous function and assigns it to a variable.
The second method creates a named function and places it within the current scope.
The third method creates a named function and assigns it to a variable. However, this time, the name only exists within the scope of that function.
Declaring a function with a name (function name () {}) has the advantage that you can then call the function more easily from inside itself, as may be necessary for implementing a recursive algorithm. If you don't, you have to use arguments.callee.name in order to call a function within itself, but that is warned against in MDN.
All of that is a long-winded way of saying that either is acceptable and, if in doubt, you can't go much wrong with using named functions.

Identifying duplicate functions in Javascript [duplicate]

This question already has answers here:
How to test for equality of functions in Javascript [duplicate]
(7 answers)
Closed 1 year ago.
Is it possible to detect duplicate functions in Javascript (which may be written by accident in some cases)? In Google Chrome,
printLah(); //this prints "Haha" for some reason, without even printing an error message in the Javascript console!
function printLah(){
alert("Hahah!");
}
function printLah(){
alert("Haha");
}
Here it is on JSfiddle.
The short answer is, no it's not.
This is how javascript works. A function name is just a variable that is assigned a function. For example:
function foo () {
alert('foo!');
}
foo = 1;
foo();
The code above will generate an error because a number is not a function! There is no difference between function names and variable names. In fact, an alternative way to define functions looks exactly like how you'd define variables:
var foo = function () {
alert('foo!');
}
It's because of this functions-as-first-class-objects behavior that javascript cannot prevent re-assignment otherwise you cannot re-assign variables (pure functional languages on the other hand have no problems with disallowing variable re-assignments).
Work-arounds and best practice:
This is the reason people keep saying that you shouldn't define too many globals in javascript. That includes functions. Otherwise it may clash by accident with someone else's code.
There are two powerful features in javascript that can mitigate this problem: objects and closures.
Because javascript supports objects you should use object oriented programming to limit the number of globals in your program. Unlike traditional OOP, javascript works better when using objects as collections or namespaces. This is because javascript doesn't have file scope and everything is global.
This doesn't mean you shouldn't create smaller objects that encapsulate smaller problems like you do with traditional OOP. It just means that you should, if you can, contain all your objects within a single parent object. And I don't mean inheritance here, I mean in a has-a relationship. Look at popular libraries like jQuery and Raphael for examples of this. They export only one object to the global scope to avoid clashing with other people's code.
But, again, this doesn't really protect people from re-assigning your objects (because they're variables after all). For example, you can easily break jQuery by doing this at the top of your HTML file before other bits of javascript have the chance to run:
jQuery = null;
The way to protect your code from being tampered with is to use a closure. Third party code has no access to any code you run from inside your closure. As long as you avoid globals that is.
Just to follow on from slebetman's answer, you can use the following to check for existence before declaring a variable or function.
if (typeof(functionName) == 'undefined') {
functionName = function() {
// add code here
}
}
Once again, the reason you would do this check is because you want/need to put something in the global scope, even though it is often not needed. Not using a var puts it implicitly into the global scope.
Try this.It work for me !!!
$(document).ready(function () {
var all_functions = [];
var duplicate_functions = [];
var reportRecipientsDuplicate = [];
for (var i in window) {
if ((typeof window[i]).toString() == "function") {
if (window[i].name) {
all_functions.push(window[i].name);
}
}
}
var all_functions1 = all_functions.sort();
for (var i = 0; i < all_functions1.length - 1; i++) {
if (all_functions1[i + 1] == all_functions1[i]) {
duplicate_functions.push(all_functions1[i]);
}
}
console.log("Duplicate functions on page");
console.log(duplicate_functions);
});

Javascript object creation best practice [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have the following javascript :
var MyObject = (function() {
function Setup(args) {
this.prop1 = args.x;
this.prop2 = args.y
this.prop3 = this.prop1 + this.prop2;
this.Create = function() {
return 'a' + helperFunc();
}
function helperFunc() {
return this.prop3;
}
}
return {
init : function(args) {
var setup = new Setup(args);
setup.Create();
}
}
})();
$(function() {
MyObject.init(someArgs);
});
Is my approach to object construction a good practice?
I am getting undefined in the helperFunc when trying to access this.prop3.
I have also tried to assign this.prop1 + this.prop2 to a local variable and use a function to return this value like so:
function Setup(args) {
var total;
this.prop1 = args.x;
this.prop2 = args.y
total = this.prop1 + this.prop2;
this.getTotal = function() {
return total;
};
this.prop3 = this.prop1 + this.prop2;
...
...and when calling this in the helperFunc like this:
return this.getTotal();
.. i get this.getTotal is not a function
I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.
TBH - I don't really understand the construct:
var myObject = (function() { ... } ();
I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?
Any knowledge imparted would be much appreciated.
Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem
To cite Xhalent's wonderful article (really well done and clearly wirtten) mentioned by him:
That is because the value of “this” is
different to the value of “this” when
the object was created.
So in your case:
...
var _this = this.prop3;
function helperFunc() {
return _this;
}
...
might achieve what's desired.
I've done a series on basic javascript fundamentals - objects and prototypes are covered here:
Javascript Object Instantation and Prototypes
I delve into Closures here:Javascript Closures
Hope they help. Cheers.
If you have a function that uses this, you must make sure that the calling context is correct. i.e. use this.helperFunc(), not just helperFunc() (but you'll also need to set things up so that this.helperFunc is defined). The referent of this inside helperFunc in your example is not the same as it is in Create().
You can think of it as though functions are not defined as members of objects, but called as members of objects.
There are three things that this might resolve to, depending on context.
A newly created object, if the function call was preceded by the new keyword.
The Object to the left of the dot when the function was called.
The Global Object (window), if neither of the above are provided.
If a function is called without an object, as in the case of your call to helperFunc in this.Create, this will be bound to the global object (window, when used in a browser)
Given something like this:
var o = {someVal:"hello"};
o.doSomething = function (){alert(this.someVal)};
Calling o.doSomething() will obviously alert "hello".
Given:
var o2 = {someVal:"world"};
o2.someFunc = o.doSomething;
Calling o2.someFunc() will alert "world", not "hello", as you would expect if it were a pointer to the doSomething member of o.
And given:
var someFunc = o.doSomething
someVal = "sailor"
Calling someFunc() will alert "sailor".
Another point of confusion is the use of this directly within Setup(). When you call a function using new, as you have done, this is not bound to the global object, but to a new instance of the Setup object.
For my example above, this means that calling new o.doSomething() will alert "undefined", as the new object that has been created for the call does not have a "someVal" member.
You have a good tutorial by Mike Koss on OOP in JS on this page.
I've seen it used a lot in jQuery
plugins but what does the first
parenth followed by empty parenth at
the end mean and do?
The second set of parenth immediatly invokes the function you have declared in the first set of parenth.
You could declare it and execute it separatly (allows to execute multiple times):
var myFunction = function() { alert("boo"); }; // Declare & instanciate
myFunction(); // Invoke
myFunction(); // Invoke again
Or do both in one line:
(function() { alert("boo"); })(); // Can only invoke now, the function is anonymous and not stored anywhere.

Categories