I am studying JavaScript and being confused with its Object concept. I used to be a Java programmer and it is terrifying me that JavaScript does not have class.
From what I've learnt so far, function can replace class in JavaScript. and you can instantiate the function by using the 'new' keyword like below.
function person() {
var name;
this.tellYourName = function() {
return 'My name is ' + name;
}
this.setName = function(newName) {
name = newName;
}
}
var person1 = new person();
person1.setName('Chris');
alert(person1.tellYourName());
in the code above, I created an object 'person1' inheriting the properties from person function.
So here's my question.
is person() an object? what I meant by object is whether the person() is a class or an instantiated object.
I was confused with this concept when I was studying closure.
Here's the sample code
function closureTest(a) {
return function(b) {
return a + b;
}
}
var test = closureTest(1);
alert(test(2));
Here I guess the closureTest function works as a method not a class. and var test = closureTest(1); line did not use the 'new' keyword. That means test variable will store the return value from the closureTest(1); But as you see the test variable is used as a an object of closureTest. How is this possible? because when I tried it with the test code below
function test(a) {
return a;
}
var t = test(2);
alert(t);
prints out the return value of the test function as I expected.
I hope my question is not too confusing. I currently moved from Java to JavaScript and my thought that they will be almost same is all wrong. I read several lectures about Object concept in JavaScript but it get even more confusing.
Thanks for your time reading this and hope I can get something from you :)
A few theoretical observations :)
The notion that an object is an instantiation of a class is pretty unhelpful for understanding JavaScript. JavaScript involves prototypal inheritance, not classical inheritance. In other words, objects inherit properties from other objects further up the inheritance chain, but not from a class.
First, functions are objects in JavaScript. This means that functions can have methods.
Second, if a function is invoked with the new prefix, then a new object is created. This new object will be linked to the function's prototype, but this will refer to the new object. Functions designed to be used with new are called constructors.
Third, there are various ways to achieve the same thing. So you can do this:
// The capital for the function indicates a constructor function
function Person(name) {
this.name = name;
}
Person.prototype.tellYourName = function() {
return 'My name is ' + this.name;
};
Person.prototype.changeName = function(newName) {
this.name = newName;
};
var person1 = new person("Chris"),
random_string = person1.tellYourName(); // Chris
Alternatively, you can achieve the same thing without using new.
function person(name) {
// myName is a private variable
var myName = name; // This line is actually unnecessary if you use name throughout
return {
// Public methods
tellYourName: function() {
return 'My name is ' + myName;
},
setName: function(newName) {
myName = newName;
}
}
}
var person1 = person("Chris"); // Note that `new` is not used
The latter is usually preferred because of the data hiding that comes with it. In other words, the only way to get at the property name is using the public methods.
I understand your confusion. The only thing that Java and JavaScript have in common is C-like syntax and the name. Other than that Java and JavaScript are two very different programming languages:
Java is a classical object-oriented programming language. JavaScript is a prototypal object-oriented programming language.
In Java functions must be methods of a class. In JavaScript functions are first-class citizens. This makes JavaScript much more powerful than Java.
Java traces its ancestry to C/C++. JavaScript traces its ancestry to Self and Scheme.
Unlike Java, JavaScript is not only an object-oriented programming language but also a functional programming language (although not as functional as Haskell or OCaml). Hence functions play a major role in JavaScript.
Functions in JavaScript may be used to:
Create a template of an object (i.e. behave like a class).
Encapsulate state and behavior (i.e. behave like a namespace).
Share functionality and reduce redundancy (i.e. behave like a mixin).
Functions as classes
JavaScript doesn't have classes because it's a prototypal object-oriented programming language. Unfortunately the prototypal nature of JavaScript is hidden behind constructors to make it look more like Java. However this only makes it difficult for Java programmers to understand inheritance in JavaScript.
For example, say you have the following Rectangle class in Java:
public class Rectangle {
public int width;
public int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int area() {
return this.width * this.height;
}
}
In JavaScript you would write the above as follows:
function Rectangle(width, height) {
this.width = width;
this.height = height;
}
Rectangle.prototype.area = function () {
return this.width * this.height;
};
If you don't like this syntax then you can make it look more like a class as follows:
function CLASS(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
var Rectangle = CLASS({
constructor: function (width, height) {
this.width = width;
this.height = height;
},
area: function () {
return this.width * this.height;
}
});
I have written a function called augment which may make your life easier.
First on the new keyword. Think of it this way: whatever you stored on this during the function body in person function, is passed when a new instance is created.
So new Person() returns this and whatever functions you have set on this
On your second problem, think of it as a function returning another function. It is returning a function, not an object. A functions is technically an object. So when you call closuretest(1), you are basically returning
var test= function(b) {
return 1+b;
}
so now if you call test(2) it becomes return 1+2 =3
Hope that helps
The examples your have shown above are two different use cases. In javascript every thing is treated as an Object. When you were using the new keyword for a function then your function Object is treated as a Class and the variable referred with this are your properties of class e.g.
var Person = function(){
this.name = null;
this.age = 0;
};
This is treated a Person Class with name and age as its properties which will be available with the instance/Object of the class Person and Object is created as
var someone = new Person();
//someone.name and someone.age are valid then.
But if not using this inside the function does not create it as a class thus it acts as a normal function as shown in your example2 which was returning another object/function which can be used.
For more clarification on this matter your should read Object oriented javascript and some more links on this topic.
When you use a 'new' key word in JavaScript it performs several steps. First of all it's creates a new instance of Object with prototype of provided function, in your case it's person. Second step is calling a provided function with bounded context of newly created object. The last step is returning a newly created object. So the magic of object creation is all in a new operator. You can read about it here
Related
I was wondering - what's the difference between JavaScript objects, classes and functions?
Am I right in thinking that classes and functions are types of objects?
And what distinguishes a class from a function? Or are they really the same thing, just the term for them changes according to how they are used?
function func() { alert('foo'); } // a function
func(); // call the function - alerts 'foo'
var func2 = function () { alert('hello'); } // acts the same way as 'func' surely?
func2(); // alerts 'hello'
var Class = function() { alert('bar'); }; // a class
var c = new Class(); // an istance of a class - alerts 'bar'
Sure, classes have methods and properties and can be instantiated - but then, I could do the same with any old function - or not?
As you must already be aware by now there are no classes in JavaScript. Instead functions in JavaScript may be made to behave like constructors by preceding a function call with the new keyword. This is known as the constructor pattern.
In JavaScript, everything is an object except for the primitive data types (boolean, number, and string), and undefined. On the other hand null is actually an object reference even though you may at first believe otherwise. This is the reason typeof null returns "object".
Functions in JavaScript are similar to functables in Lua (i.e. they are callable objects). Hence a function can be used in place of an object. Similarly, arrays are also objects in JavaScript. On the other hand, objects can be thought of as associative arrays.
The most important point however is that there are no classes in JavaScript because JavaScript is a prototypal object-oriented language. This means that objects in JavaScript directly inherit from other objects. Hence we don't need classes. All we need is a way to create and extend objects.
Read the following thread to learn more about prototypal inheritance in JavaScript: Benefits of prototypal inheritance over classical?
Update 2015
There are classes in JavaScript they just aren't used on older browsers:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
It has constructors, extensions, and the like.
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Lion extends Cat {
speak() {
super.speak();
console.log(this.name + ' roars.');
}
}
A Class in JS:
function Animal(){
// Private property
var alive=true;
// Private method
function fight(){ //... }
// Public method which can access private variables
this.isAlive = function() { return alive; }
// Public property
this.name = "Joe";
}
// Public method
Animal.prototype.play = function() { alert("Bow wow!"); }
// .. and so on
Now when you create it's object
var obj = new Animal();
You can expect anything of this object as you would from objects in other language. Just the efforts to achieve it, was a bit different. You should also be looking at inheritance in JS.
Getting back too your question, I'll reword it as:
//Class : A representation of a set with common properties.
//object : One from the set with the same properties.
var Class = function() {alert('bar');}; // A set of function which alert 'bar'
var object = new Class(); // One of the functions who alert's 'bar'.
JavaScript does not have classes, and functions are actually objects in JavaScript (first-class citizens).
The only difference that function objects have is that they are callable.
function func() { alert('foo'); } // a function - Correct
func(); // call the function - alerts 'foo' - Correct
var func2 = function () { alert('foo'); } // same as 'func' surely? - Nope, func2 is a different object, that apparently does the same thing when called.
var Class = function() { alert('bar'); }; - It's a function with no name stored in variable Class.
var c = new Class(); - Calls function stored in Class supplying new empty object as this and returning that object. Functions called as new functionA() are expected to work as constructors and prepare a newly created object (this). In your case - constructor does nothing with the object and just alerts bar.
You also get classes in ES6 that look like this:
//class
class Cat {
//constructor
constructor() {
this.name = 'Snowball';
}
//method
meow() {
console.log('Hello, nyah! My name is ' + this.name + ' nyah!~');
}
};
There are no classes in javascript. But, there are ways to make a function to behave like a class in other languages.
A very good explanation is given here 3 way to define a class in js
Also, found a very good reference for OOP in Javascript
Object is the base type in JavaScript i.e. all the user defined data types inherits from Object in one way or another. So if you define a function or a class [note as of now JS doesn't support class construct, but its proposed in ECMAScript version 6], it will implicitly inherit from Object type.
Classes are really used for encapsulating logical functions and properties into one type / entity and you can 'new' it up using constructor syntax. So if you define a 'Customer' class, you can instantiate it multiple times and each instance / object can have different values. They can even share the values if you define class level value using prototype.
Since JS doesn't support class construct at the moment, functions can really act as individual method as well as container for other functions or types.
I hope with ECMAScript 6 we will have clear separation between these constructs similar to what we have in other languages like C#, Java etc.
Parasitic Constructor Pattern can be seen as a combination of factory and constructor pattern.
In factory pattern, we call a function which then explicitly creates an object and adds desired properties and methods to the object and finally returns the object.
function createPerson(name, age, job){
var o = new Object(); //explicit object creation
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}
var person1 = createPerson(“Nicholas”, 29, “Software Engineer”);
var person2 = createPerson(“Greg”, 27, “Doctor”);
Things to note:
explicit object is created and returned
method and properties are added to the explicitly created object
method is called without new keyword
The disadvantage: it doesn’t allow to identify the type of the object.
Any function can be treated as constructor by calling it with new operator. When called without new operator, inside the function, this object points to the global object (window in browser). And when the function is called with the new operator, it first creates the new instance of object and then sets this object to a newly created object.
Constructor pattern adds methods and properties to this object and finally returns this object thus allowing to later identify the type of the object using instanceOf operator.
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var person1 = new Person(“Nicholas”, 29, “Software Engineer”);
var person2 = new Person(“Greg”, 27, “Doctor”);
Things to note:
function is called with new operator (to make JavaScript engine treat it as a constructor)
object is not created explicit instead this object is returned
Now the Parasitic Constructor Pattern explicitly creates and returns an object similar to factory pattern and it is called with new operator like constructor pattern:
function Person(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}
var friend = new Person(“Nicholas”, 29, “Software Engineer”);
friend.sayName(); //”Nicholas”
However I can't see the use of calling the function with new operator. I mean since the function explicitly creates and returns the object we will not be able to identify the object type explicitly using instanceOf operator.
So what is great in Parasitic Constructor pattern? Is there any technical subtlety that can be exploited or suitably used for a specific object creation scenario? Or Is just another possible programmatic approach for creating object?
I think the part that you're skipping over with the Factory, is that in most other languages, the factory is either going to be making multiple different kinds of similar objects, whether done like:
var truck = carFactory("Truck");
var jeep = carFactory("Jeep");
or done like:
var piano = instrumentFactory.piano("Grand");
var bass = instrumentFactory.bass("Upright");
or any other interface you want it to have...
OR a factory's responsibility is going to be to make a very big class out of smaller classes, through dependency-injection, and potentially polymorphism:
function createTank (gunType) {
var armour = new Armour();
armour.hp = 120;
var wheels = new ChainTracks();
var driver = new Soldier();
driver.hp = 15;
var gun = gunFactory(gunType);
var tank = new Tank(armour, wheels, gun);
tank.driver = driver;
return tank;
}
var ground_tank = createTank("cannon");
var aa_tank = createTank("flak_cannon");
var at_tank = createTank("depleted_uranium_lancer");
If you have a Factory which is as simple as making an object, setting its properties and returning the object, then there really is no difference.
The differences come into play when you're either talking about using a lot of specialized components to make something come together (whether they're injected, or hard-coded), or you're dealing with inheritance.
And honestly, I'd suggest learning more about those things (object composition and inheritance), before looking too much further at different ways of doing them.
Because ultimately, it doesn't make any difference to the finished code, if you used a factory, or if you used a function which modified a generic object, or if you just used a whole lot of classes in the middle of your code... The program will run great, or will die, any way you slice it.
Where it does make a difference is in how you organize your code, and how you compose your code.
You don't really need a factory if all you're doing is making a button on the page.
If you're making a full-featured MP3 player on your page, which needs 6 buttons, a play-list, a progress-bar and a display for track name, artist name and cover art...
...NOW is a great time to start looking into factory patterns for figuring out how to put those pieces together, to ask for one thing, and have it spit out the finished product, off the assembly line.
I think from your perspective there isn't much of a difference, but if you go one step further and implement the abstract factory pattern, or you start to polymorph your factories, you can save a lot of work every time you write a new one.
In javascript, since you can set any value to an object because the language doesnt have private values, factories can be verry powerfull and inherit most of its logic from base-classes if you work with a framework that supports OOP standarts for objects.
EDIT
Ok, one thing, in my eyes one of the most important when it comes to JavaScript and those patterns, is prototyping.
prototyping is basicly the way you define objects in javascript so the runtime actually recognizes the object and can tell it apart from other objects.
basicly only using prototypes looks like this:
var Person = function(name){
this.name = name
}; //constructor
Person.prototype.constructor = Person;
Person.prototype.name = 'Dave';
Person.prototype.getName = function() {
return this.name;
}
some test code:
var dave = new Person('Dave');
console.log(dave.getName());
and finally a factory:
var PersonFactory = function(name) {
return new Person(name);
}
Now the problem with that anotation usually is that it is poorly maintainable and it features no inheritance.
Now comes what most frameworks to:
You can create helper functions building up your prototypes and even build a prototype chain. basicly you define an object that takes in another object and it resolves the other objects members into the prototypes of the desired class object, leaving open all sorts of possibilitys for inheritance etc.
some examples can be found here:
http://www.ruzee.com/blog/2008/12/javascript-inheritance-via-prototypes-and-closures
i like the way mootools handles classes:
var MyClass = new Class({
Extends: MyOtherClass
Implements: [MyInterface, MyOtherInterface],
myPublicValue: null,
myOtherValue: null,
initialize: function() {
//constructor
},
doStuff: function() {
return 'stuff done';
}
});
Drawbacks of the mootools class system itself:
-Closure Compiler doesnt like trailing commas, you tend to leave them in your code
-Allmost no IDE supports autocompletion for mootools classes (because the prototypes arent
annotated in a file, could be resolved using scripts to resolve your classes into prototyped files)
Now with this there are tons of design desicions you could go for, let your factories inherit from your own prototype helper class, using the prototype helper class to create the actual factory (some recursion in here), you could resolve each object on its creation (lazy loading like) or resolve every class object on page load (be carefull, if you go into inheritance, in most implementations of it classes you derive from must be resolved first)
or go any way possible.
i hope that helped out :)
(and sorry for my bad english right now, im pretty tired tonight xD)
If I have a function say:
var my_function = function()
{
}
If the function is not called, it is not taking up memory, it is just text sitting in memory.
However if you call it by say...
function_instance = new my_function();
It is instantiated is a sort of way, and the variables and methods it contains are loaded into memory.
Is this a way to represent a class/object model similar to C++?
Is my interpretation correct?
In javascript, the class concept does not exist. Everything is an object. When you use the new operator it copies the prototype of that function into a new object. In other words, you can emulate what class can do in c++, but it's not a class.
"a way to represent a class/object model similar to C++" would be through the use of prototypes.
As Kevin M pointed out, you can use the this keyword to create instance variables in a function, like so:
var my_function(foo)
{
this.foo = foo;
this.bar = function()
{
// bar-ing here
}
}
The problem however, that whenever you instantiate my_function(), a new instance of the my_function.bar function is also created. Enter prototypes:
var barPrototype = { "bar" : function()
{
// bar-ing here
}
};
var my_function(foo)
{
this.foo = foo;
}
my_function.prototype = barPrototype;
So, to sum it all up, the prototype keyword can be used to create function-specific, inheritable properties that are analoguous to C++'s member functions. Member functions of C++ aren't instantiated for each instance of a class. Instead, the compiler adds a this pointer to the function's parameters; this pointer points to the instance that the member function is called on.
More JSey fun to be had here: http://javascript.infogami.com/Javascript_in_Ten_Minutes
In JavaScript a new class is defined by creating a function. The function may contain other functions (methods), properties, etc.
When a function is called using the new operation the function becomes a constructor for that class. Inside the constructor the variable " this " is created and points to the object.
function Man(){
this.name = 'John';
}
var person = new Man;
console.log(person.name);
As mentioned, Javascript functions can act as objects so Javascript can be object oriented but object inheritance is prototypical and not like C++. John Resig, the creator of jQuery, has done some work on emulating traditional classes and inheritance in javascript. You could take a look at his blog for an interesting example:
http://ejohn.org/blog/simple-javascript-inheritance/
I'm hesitant to use just any tutorial because I know how those tutorials can end up being, teaching you bad ways to do things. I want to setup a class in Javascript, so that I can just do
var vehicle = new Vehicle(el);
var model = vehicle->getModel();
These functions would read the HTML and get and manage the elements on the page. I'm current doing a setup like...
var model = function () {
return {
getName: function () {
},
getVehicleCount: function () {
},
incrementCount: function (id) {
console.log(x);
}
}
}();
I'm still learning classes in Javascript... I'd like to be able to pass the class a node for the element all of the methods will use, but I'm not sure I'm doing this right...
There is no such thing as a class in JavaScript, instead everything in JavaScript is an object.
To create a new object you define a function that uses the this keyword in it (a “constructor function”), and then call it with the new operator:
function Foo (id) { // By convention, constructor functions start with a capital letter
this.id = id;
}
var foo1 = new Foo(1);
var foo2 = new Foo(2);
However, these objects have no methods. To add methods, you need to define a prototype object on their constructor function:
Foo.prototype = {
getId: function () {
return this.id;
}
}
This new getId function will be usable by all Foo objects. However, as was stated, there are no classes in JavaScript and as such there are other constructs you will use in order to produce different results.
I highly recommend the videos by Douglas Crockford in which he explains much of the javascript OO nature. The talks can be found here:
http://developer.yahoo.com/yui/theater/
Douglas Crockford — The JavaScript Programming Language
Douglas Crockford — Advanced JavaScript
Those will give you a basic understanding of the structure of javascript and should help the transition from classical to functional programming.
Although there are no classes in JavaScript, you can create constructor functions. A constructor function works by binding methods to an objects prototype. There are several ways to do this, each with advantages and disadvantages. I personally prefer the most straigthforward way, which works by appending methods to "this":
var Constructor = function() {
//object properties can be declared directly
this.property = "value";
//to add a method simply use dot notation to assign an anonymous function to an object
//property
this.method = function () {
//some code
}
//you can even add private functions here. This function will only be visible to this object methods
function private() {
//some code
}
//use return this at the end to allow chaining like in var object = new Constructor().method();
return this;
}
There is nothing like classes in JavaScript. JavaScripts inheritance works with prototypes. You can take a look at base2, which mimics class-like behaviour in JavaScript.
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.
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 > 17;
};
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.
Javascript supports objects but not classes - it uses a prototype-based object system.
JavaScript supports object-oriented development
Object-oriented JavaScript
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.
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.
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;
}
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.