views:

832

answers:

7

I found the following code somewhere, but I am not understanding the code properly.

ArticleVote.submitVote('no');return false;

Is ArticleVote a class and submitVote() a function of that class?

Or what does the above code mean? And is there any concept of classes and objects in jQuery or in traditional JavaScript? How to create them? Please share some reference links or code.

+10  A: 

Javascript supports objects but not classes - it uses a prototype-based object system.

Greg
A: 

You can achieve the above through Javascript, nothing to do with jQuery.

var ArticleVote= {}; 

ArticleVote.submitVote = function(voteResult) {
    console.log(voteResult);
}


function Vote(){
   ArticleVote.submitVote('no');
   return false;
}
redsquare
+1  A: 

Yes, JavaScript has impressive support for Object Oriented programming, Objects and functions. In fact, I'm surprised that you have to ask this question! There are a wealth of resources online such as:

http://mckoss.com/jscript/object.htm

http://www.webreference.com/js/column79/

http://www.javascriptkit.com/javatutors/oopjs.shtml

More resources: http://www.google.com/search?q=object+oriented+programming+javascript

JavaScript frameworks such as jQuery and Prototype could not have been built without this support in JavaScript engines.

Cerebrus
I'm not sure I would use the term "impressive". Most of the work that went into the defunct 4th ECMAScript edition (which never reached full standard status, but nonetheless was used for JScript.NET, and a few other implementations out there). One of the explicit purposes of the 4th revisions was to introduce a more classical class based approach to OOP, and to better support "programming in the large".JS is a great language, and it certainly is OOP (just not class based OOP). But you do often need to jump through (alot of) hoops to get what you want.
Svend
I agree with this
Pierreten
+38  A: 

Everything is an object in JavaScript

As opposed to other purportedly pure OOP languages. Functions are objects too, but they may just as well be constructor of objects.

var ObjectCreator = function () {
};

The above is a function which if called appropriately, creates an object. Called appropriately means that you have to use the new operator:

var obj = new ObjectCreator;

So while JavaScript does not have classes per se, has means to emulate that behavior. For example:

class Foo {
    public void bar() {}
}

Foo foo = new Foo();

is equivalent to the following JS code:

var Foo = function () {
    // constructor
};

Foo.prototype.bar = function () {}

var foo = new Foo;

Inheritance is different

The real difference comes when you want to use inheritance, which is a different type of inheritance (prototypal). So, given two pseudo-classes Foo and Bar, if we want Bar to extend from Foo, we would have to write:

var Foo = function () {};
var Bar = function () {};

Bar.prototype = new Foo; // this is the inheritance phase

var bar = new Bar;

alert(bar instanceof Foo);

Object literals

While constructor functions are useful, there are times when we only need only one instance of that object. Writing a constructor function and then populate its prototype with properties and methods is somehow tedious. So JavaScript has object literals, which are some kind of hash tables, only that they're self-conscious. By self-conscious I mean that they know about the this keyword. Object literals are a great way to implement the Singleton pattern.

var john = {
    age : 24,

    isAdult : function () {
        return this.age > 17;
    }
};

The above, using a constructor function would be equivalent to the following:

var Person = function (age) {
    this.age = age;
};

Person.prototype.isAdult = function () {
    return this.age = age;
};

var john = new Person(24);

What about that prototype thingy

As many have said, in JavaScript objects inherit from objects. This thing has useful aspects, one of which may be called, parasitic inheritance (if I remember correctly the context in which Douglas Crockford mentioned this). Anyway, this prototype concept is associated with the concept of prototype chain which is similar to the parent -> child chain in classical OO languages. So, the inheritance stuff. If a bar method is called on a foo object, but that object does not have a bar method, a member lookup phase is started:

var Baz = function () {};

Baz.prototype.bar = function () {
    alert(1);
};

var Foo = function () {};
Foo.prototype = new Baz;

var foo = new Foo;

/*
 * Does foo.bar exist?
 *      - yes. Then execute it
 *      - no
 *          Does the prototype object of the constructor function have a bar
 *          property?
 *              - yes. Then execute it
 *              - no
 *                  Is there a constructor function for the prototype object of
 *                  the initial construct function? (in our case this is Baz)
 *                      - yes. Then it must have a prototype. Lookup a bar
 *                        member in that prototype object.
 *                      - no. OK, we're giving up. Throw an error.
 */
foo.bar();

Hold on, you said something about parasitic inheritance

There is a key difference between classical OO inheritance and prototype-based inheritance. When objects inherit from objects, they also inherit state. Take this example:

var Person = function (smart) {
    this.smart = smart;
};

var Adult = function (age) {
    this.age = age;
};

Adult.prototype = new Person(true);

var john = new Adult(24);

alert(john.smart);

We could say that john is a parasite of an anonymous Person, because it merciless sucks the person intelligence. Also, given the above definition, all future adults will be smart, which unfortunately is not always true. But that doesn't mean object inheritance is a bad thing. Is just a tool, like anything else. We must use it as we see fit.

In classical OO inheritance we can't do the above. We could emulate it using static fields though. But that would make all instances of that class having the same value for that field.

Ionuț G. Stan
Great very detailed answer.
Pim Jager
Thanks! Though I find it a bit incomplete. JavaScript has some gotchas in regard to its prototypal inheritance.
Ionuț G. Stan
+1  A: 

Certainly JS has objects and classes, but it's not exactly a conventional approach.

It's rather a broad question, but there's three main things you want to know about objects and classes in JS:

1). Everything is an object - this famously includes JS's first class functions

2). There are object literals

var myObject = { "foo": 123, "bar": [4,5,6] };

3). Inheritance is prototype based, so creating classes is more a matter of form than function. To get the effect of a class you'd write something like:

function myClass(foo)
{
  this.foo = foo;
}
myClass.prototype.myFooMethod = function() {alert(this.foo);}

var myInstance = new myClass(123);

myinstance.myFooMethod(); // alerts 123

For your example it's likely that ArticleVote is an object instance and probably not conceptually a class, and submitVote would be a method of the object. can't tell for sure though, it could be what you'd call a static method in another language.

annakata
Don't call it an orange when its a brick. (Javascript doesn't have classes! (yet!))
ironfroggy
for all practical intent this is class implementation in JS - and I'm not hardly the only one with that view, see Ionut G. Stan's answer
annakata
JavaScript may not have oranges, but it certainly has some sort of citric fruit.
Ionuț G. Stan
nice :D
annakata
A: 

You can use the JavaScript function as class.

ClassUtil = function(param){

  privateFunction = function(param){

 // Do some thing

 return valueParam;
}

this.publicFunction = function(){

 var val1 = function1();

 if (val1){

  return true;

 }else{

  return false;
 }
}

}

function getClass(){

var classUtil = new ClassUtil();

alert(classUtil.publicFunction());

}

There is one public and one private function. You can call public function from out side using object of the class.

Umesh Aawte