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.
Related
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
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.
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/
What are the basic ways of defining reusable objects in Javascript? I say reusable to exclude singleton techniques, such as declaring a variable with object literal notation directly. I saw somewhere that Crockford defines four such ways in his book(s) but I would rather not have to buy a book for this short bit of information.
Here are the ways I'm familiar with:
Using this, and constructing with new (I think this is called classical?)
function Foo() {
var private = 3;
this.add = function(bar) { return private + bar; }
}
var myFoo = new Foo();
Using prototypes, which is similar
function Foo() {
var private = 3;
}
Foo.prototype.add = function(bar) { /* can't access private, correct? */ }
Returning a literal, not using this or new
function Foo() {
var private = 3;
var add = function(bar) { return private + bar; }
return {
add: add
};
}
var myFoo = Foo();
I can think of relatively minor variations on these that probably don't matter in any significant way. What styles am I missing? More importantly, what are the pros and cons of each? Is there a recommended one to stick to, or is it a matter of preference and a holy war?
Use the prototype. Returning specific objects from constructors makes them non-constructors, and assigning methods to this makes inheritance less convenient.
Returning an object literal
Pros:
If a person forgets new, they still get the object.
You can create truly private variables, since all methods of the object defined inside the constructor share its scope.
Cons:
It’s not a real constructor. Adding something to its prototype won’t change the returned objects, new or no new. new Foo() instanceof Foo would also result in false.
Using prototype
Pros:
You leave the constructor uncluttered.
This is the standard way of doing things in JavaScript, and all built-in constructors put their methods on their prototypes.
Inheritance becomes easier and more correct; you can (and should) use Object.create(ParentConstructor.prototype) instead of new ParentConstructor(), then call ParentConstructor from within Constructor. If you want to override a method, you’re able to do it on the prototype.
You can “modify” objects after they’ve already been created.
You can extend the prototypes of constructors you don’t have access to.
Cons:
It can get to be a bit too verbose, and if you want to change the function’s name, you have to change all of the functions added to the prototype, too. (Either that or define the prototype as one big object literal with a compatible property descriptor for constructor.)
They don’t share an instance-specific scope, so you can’t really have private variables.
Assigning to this.* in the constructor
Pros:
You can use closures and therefore private member variables.
Cons:
No duck typing; you can’t call a method right off of the prototype with any old object. For example, Array.prototype.slice.call(collectionLikeObject).
It's mostly a matter of preference. There's no one way to make Chicken Noodle soup, and uniform objects are the same way.
I don't use any of those 3, although they all work for their own purposes. I use a custom function called Object:deploy, and use it like this..
var a = { hey: 'hello' },
b = {}.deploy(a);
console.log(b.hey); // 'hello'
Using prototype is the best for most people because of automatic trickling.
function A() {};
A.prototype.hello = "Hey";
var a = new A();
console.log(a.hello); // 'Hey'
A.prototype.hello = "Hello";
console.log(a.hello); // 'Hello'
And contrary to popular belief, you can use private variables in prototype.
function Hello() {};
(function () {
var greeting = "Hello";
Hello.prototype.greet = function () { return greeting };
}).apply(this);
But even though that's possible, it's usually better to do..
function Hello() {};
Hello.prototype.greeting = "Hello";
Hello.prototype.greet = function () { return this.greeting };
Well the second approach (prototype) is more similar to standard classes in other languages like Python, in that you have a common "prototype" object which all instances are sharing. To compare the first and second approaches:
In approach 1, every time you call "new Foo()", you are creating a brand new object and inserting all the methods. This isn't very time or space efficient, since each Foo instance will have its own table of all the methods. You can test this by creating two Foo objects, and asking foo1.add == foo2.add (false). Approach 3 is very similar to this; I'm not sure what the semantic difference (if any) there is between approaches 1 and 3.
In approach 2, you have set up a shared prototype object containing all the methods. If you ask foo1.add == foo2.add, you get true. This is more space- and time-efficient. It also lets you add more methods to the prototype after creating instances, and they will see the new methods.
The problem with approach 2, as you say, is that you can't access the private members. But you can still add non-private members to the object itself, and access those using the prototype methods:
function Foo() {
this.private = 3;
}
Foo.prototype.add = function(bar) { return this.private + bar }
A caveat is that foo.private is visible externally.
The prototype one doesn't have a per object instance overhead only a per class overhead for the add function. This alone is the reason why I don't like the other two approaches.
Do not forget about inheritance. Some day you'll need. And for organizing inheritance the best approach is combined technic:
function Foo() {
this.array = [1, 2, 3];
this.add = function(bar) { return private + bar; }
}
Foo.prototype.add = function(bar) { }
var myFoo = new Foo();
Setting fields in constructor is useful to avoid modifying them by children objects.
Setting methods to prototype is faster then doing this every time in constructor.
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.