Method implementation difference.. need some understadning - javascript

Excuse me first. because i don't know this is question is valid or not. i if any one clear my doubt then i am happy.
Basically : what is the different between calling a method like:
object.methodname();
$('#element').methodname();
calling both way is working, but what is the different between, in which criteria make first and second type of methods. is it available in the core javascript as well?
In case if i have a function is it possible to make 2 type of method call always?
Can any one give some good reference to understand correctly?
Thanks in advance.

The first syntax:
object.methodName();
Says to call a function, methodName(), that is defined as a property of object.
The second syntax:
$('#element').methodname();
Says to call a function called $() which (in order for this to work) must return an object and then call methodname() on that returned object.
You said that "calling both way is working," - so presumably you've got some code something like this:
var myObject = $('#element');
myObject.methodname();
This concept of storing the result of the $() function in a variable is commonly called "caching" the jQuery object, and is more efficient if you plan to call a lot of methods on that object because every time you call the jQuery $() function it creates another jQuery object.
"Is it available in the core javascript as well?" Yes, if you implement functions that return objects. That is, JS supports this (it would have to, since jQuery is just a JS library) but it doesn't happen automatically, you have to write appropriate function code. For example:
function getObject() {
return {
myMethod1 : function() { alert("myMethod1"); return this; },
myMethod2 : function() { alert("myMethod2"); return this; }
};
}
getObject().myMethod1().myMethod2();
In my opinion explaining this concept in more depth is beyond the scope of a Stack Overflow answer - you need to read some JavaScript tutorials. MDN's Working With Objects article is a good place to start once you have learned the JS fundamentals (it could be argued that working with objects is a JS fundamental, but obviously I mean even more fundamental stuff than that).

The difference is very subtle.
object.methodname();
This is when JavaScript has the object at hand.
$('#element').methodname();
If you are using jQuery, you are asking jQuery to select the object that has the id of #element. After that you invoke the method on the selected object.

Related

Is it possible to give a type/class to JavaScript functions?

I wonder if it's possible to give a a type/class to JavaScript functions.
Of course, the Object class/type of function is 'Function/function'.
http://bonsaiden.github.io/JavaScript-Garden/#types.typeof
However, in my project, somehow I want to define class for function to group them.
It's similar concept HTML/CSS DOM element class.
I have a function which args is a function, and I want to distinguish which type or class of function is passed to the function.
It does not work with any object method, just a function, but it can be distinguished like obj.hasOwnProperty('someClass') .
I just wonder if there's smart way, if you think impossible, please insist so.
Thanks.
PS. I do not why someone vote -1 and to close this question.
This is the matter of reflection of Javascript. It's ok if find some reflection factor of JS is limited. and I think it's not wise to avoid to make it clear that something is impossible in a certain language.
A function is an object. You can add your own custom properties to any function. So, if you want to set your own type on several different functions so you can test for that, you can just add the same custom property (with different values assigned to it) to each of those functions.
function myFunc1() {}
myFunc1.myType = "whatever1";
function myFunc2() {}
myFunc2.myType = "whatever2";
function myFunc3() {}
myFunc3.myType = "whatever3";
function callMe(cb) {
if (cb.myType === "whatever1") {
// code here
} else if (...) {
// code here
}
}
callMe(myFunc1);
Note, this is a bit unusual and if you explained the actual problem you were trying to solve, there is probably a more common design pattern that might help you.
#jfriend00 has suggested the answer.
FYI, functions are objects so they can have your own custom properties so you could make your own custom property.
He's right, so to add a class/property to any functions, simply do
var myFunction = function(foo){...};
myFunction['someClass'] = true;
//To distinguish
if (someFunction.hasOwnProperty('someClass'))
{
console.log('someFunction is someClass');
}

Understanding method chaining in javascript

I want method chaining to work, but it seems i'm not getting some concepts.
This:
$(".list").activeJS()
first has to use jQuery to get a HTMLElement nodelist and then it has to call the activeJS() function passing the nodelist.
var activeJS = function(item){
alert(item) //nodelist
}
Now i get a TypeError: $(...).activeJS is not a function error in my console.
Thx,
If you want to create a function callable from a jQuery object, you have to add it to the jQuery prototype object:
jQuery.fn.activeJS = function(item) {
// ... whatever
};
When a function is added to jQuery (which allows for chaining) it is referred to as a plugin and several things must be taken into consideration. For example, is your function itself chainable? Will your function work on a single element or multiple? I would recommend that you research jQuery plugins and build your function as a plugin in jQuery.
Here is an excellent tutorial on building a jQuery plugin that covers concepts such as chaining, passing properties and calling different plugin functions. Take a look at the article and determine if your function truly needs to be a plugin.
It may be better to simply pass jQuery and the selected elements as arguments to your function instead of chaining.
Take a look at this example:
var obj = {
fn: function(){
console.log("fn method");
return this;
},
abc: function(){
console.log("abc method");
return this;
},
oneMore: function(){
console.log("one more method");
return this;
}
};
Here chaining is provided by returning reference to obj Object.
Simply, every time you call a method on that object, you are returning that object - and you can continue calling its methods. This is basic chaining pattern that you can find in jQuery also - slightly modified but the idea is same. Thanks to dynamic nature of javascript we can do this kind of things. Chaining allows coupling of related methods that are connected by common object. This pattern has its roots in functional programming, and javascript is heavily influenced by functional languages (mostly scheme).
But too much chaining can lead to unreadable code as can be seen in lot of jQuery examples.

Is this bad practice: getMyObject().method()

Suppose I have a function which returns an object :
getMyObject(){
//do stuff here
return object;
}
Is it bad practice to call a method (that doesn't return anything) on the function name itself:
getMyObject().method();
instead of assigning a variable to the return object and then calling the method on that variable :
var returnedObject = getMyObject();
returnedObject.method();
I am working with an html page that has many nested frames, and I have access to a function that returns one of these frames. The frame might be used several times within other functions in my script, and I was wondering if it would be ok for me to access the frame in the way asked above, or if it would be better to declare a global variable.
*EDIT: * Ahh I haven't gotten a chance to use jQuery. Good to know!
Yes, this is perfectly OK. jQuery for example uses this as well. It returns objects on which you can call methods immediatley. This is called chaining.
In your example, method chaining is the better practice IMHO. If a function returns an object, upon which you want to call a method, but you do not need to reference that object after calling that method, don't assign it to a variable.
Also, jQuery code does this all the time(1):
$('#foo').on('click',function(){});
/\ \\
|| \\
|| \\
function call returns jQ object <============|
\\ ||
\\call method "on" upon _||
(1)To clarify: I do not claim that all jQ methods return an object .attr() or .prop() don't. What I mean by "all the time" is actually that the scenario the OP describes is very common in jQ code (function call, invoke method on returned object):
var someString = $($('.foo').get(0)).attr('id');//tricky little bugger, this :)
var aBool = $('#foo').prop('checked');
Usually, no. Chaining method calls like that is usually simpler, more elegant, and easier to read. However, there are a few cases when it's better to use a variable.
If you use a method (or chain of methods) a lot of times, you can use a variable if it makes the code cleaner.
If the method takes a long time to process, it's better to cache the result. For example, if you have some method called calculateResults(), and it pulls data from a database, that takes some time. If the data doesn't change, you'll be incurring that cost for each call to the method. Better to store it in a variable and reuse it.
If the method has side effects, you should be careful about calling it more than once. Those side-effects will be inflicted each time you call it. Again, as an example, if you have a function like nextItem() that advances to the next item and returns it (a la Java iterators), then calling it more than intended will actually change the result. In this case, you have no choice but store the result, since calling it more than once will produce incorrect behavior.
Otherwise, chain away!

javascript to jquery conversions

I have a JavaScript function which returns a function. What does it mean ?
function CheckShadowBounds(rounded) {
return function() {
};
}
How can I convert it to jQuery ?
It means it returns a function. Functions are first class objects and can be passed around just like strings, arrays, etc, etc.
The purpose of this example is to define rounded for the function. The same instance of rounded will be used every time the returned function is called.
You can't convert it to jQuery. jQuery is a set of predefined JavaScript functions that do things lots of people want to do, but which are relatively complex (often because of browser incompatibilities). This is not something that is relatively complex, so jQuery doesn't provide a helper function.
See Joel Spoelsky's intro to functional programming in JS to understand some ways a function returning a function can be useful: http://www.joelonsoftware.com/items/2006/08/01.html
This shouldn't need any changes to work in JQuery.

Javascript plugins design pattern like jQuery

Could someone write down a very simple basic example in javascript to conceptualize (and hopefully make me understand) how the jQuery plugin design pattern is done and how it works?
I'm not interested in how creating plugin for jQuery (so no jQuery code here at all).
I'm interested in a simple explanation (maybe with a bit of Javascript code) to explain how it is done the plugin concept.
Plz do not reply me to go and read jQuery code, I tried, but I it's too complex, otherwise I would have not post a question here.
Thanks!
jQuery has a library of functions stored in an internal object named fn. These are the ones that you can call on every jQuery object.
When you do $("div.someClass") you get a jQuery object containing all <div> elements of that class. Now you can do $("div.someClass").each( someFunction ) to apply someFunction to each of them. This means, that each() is one of the functions stored in fn (a built-in one in this case).
If you extend (add to) the internal fn object, then you automatically make available your custom function to the same syntax. Lets assume you have a function that logs all elements to the console, called log(). You could append this function to $.fn, and then use it as $("div.someClass").log().
Every function appended to the fn object will be called in such a way that inside the function body, the this keyword will point to the jQuery object you've used.
Common practice is to return this at the end of the custom function, so that method chaining does not break: $("div.someClass").log().each( someFunction ).
There are several ways to append functions to the $.fn object, some safer than others. A pretty safe one is to do:
jQuery.fn.extend({
foo: function() {
this.each( function() { console.log(this.tagName); } );
return this;
}
})
Tomalak already posted almost everything You need to know.
There is one last thing that helps jQuery do the trick with the this keyword.
it's amethod called apply()
var somefunction=function(){
alert(this.text);
}
var anObject={text:"hello"};
somefunction.apply(anObject);
//alert "hello" will happen
It really helps in creating abstractions so that framework/plugin users would just use this as intuition tells them, whatever there is inside Your code
It works, as many other js frameworks, using javascript prototype orientation.
For instance you can declare a simple function
var alertHelloWorld = function() {
alert('hello world');
}
And then tie it to an existing object (including DOM nodes)
document.doMyAlert = alertHelloWorld;
If you do this
document.doMyAlert();
The alertHelloWorld function will be executed
You can read more about javascript object prototyping here

Categories