This question already has answers here:
How can I emulate "classes" in JavaScript? (with or without a third-party library) [closed]
(7 answers)
Closed 10 years ago.
I have searched for a way of defining a class in javascript like in java or php but I found none!
I want something like
class javascriptClass {
function someFunction(){}
}
You can use a prototype class, like so:
function MyClass() {
}
MyClass.prototype.method1 = function() {
// do stuff
};
MyClass.prototype.method2 = function(p) {
// do stuff
};
var myClass = new MyClass();
Now, after instantiating an object myClass from the prototype MyClass, you can access the methods of the object myClass:
myClass.method1();
The above method is great if you need to instantiate more than one object/instance of the class.
If you only expect to have one object, then another method you can use simply acts as a namespace to protect your functions from collisions with others:
var myObject = {
method1: function() {
// do stuff
},
method2: function(p) {
// do stuff
}
};
myObject.method1();
In JavaScript, you don't have classes as such. You define functions that are used to create objects with new, and you can give them methods by either creating them in the body of the constructor, or adding them through the object's prototype. For example:
function JavaScriptClass() {
// I am a JavaScript constructor! Any initialization can be done here.
}
// This is the prototype! You can put instance methods and variables (to an extent) here.
JavaScriptClass.prototype.someFunction = function() {
alert('someFunction was called!');
};
// Now, let's create an instance!
var obj = new JavaScriptClass();
obj.someFunction(); // someFunction was called!
And you can access the current object using this, in both the constructor and any methods bound to the object. Note that this can also be bound to just about anything in JavaScript. It's a different type of OOP.
Unlike class-based languages, JavaScript is functional languages or prototypal language, you can't use class keyword or the kind of signature you have posted in JavaScript. In JavaScript, normally you would do:
function Person(){
// public members
this.foo = 'foo';
this.walk = function(){ ......... }
// private members
var bar = 'bar';
var baz = function(){.........}
}
var person = new Person();
Related
This question already has answers here:
Use of 'prototype' vs. 'this' in JavaScript?
(15 answers)
Closed 8 years ago.
Say I have the following Function
function FooController (){
this.foo = function () {
alert('foo');
}
}
FooController.prototype.bar = function () {
alert('bar');
}
Is there a difference between these two syntaxes? Why would I use one over the other? Is there a performance hit?
If it's defined on the prototype, any instance of FooController will "inherit" the bar method because it's in the instance's prototype chain. Only 1 function is defined and in memory using this technique.
If you define using this.foo = function, you're adding the function directly to the instance as a property of that instance. This means that you will have 1 function in memory per instance of the controller.
function FooController {}
FooController.prototype.hello = function() {
console.log("world");
};
Create an instance and check the prototype's value
var c = new FooController();
c.hello(); // "world"
This is as expected, but let's define a hello method directly on the c instance
c.hello = function() { console.log("cats"); };
c.hello(); // "cats"
We can still call the prototype method directly
c.prototype.hello.call(c); // "world"
Or we can delete the hello property on the c instance
delete c.hello;
Now let's call our function again
c.hello; // "world"
It's back to using the prototype's method !
All instances of FooController will share bar, each foo will be created individually per object.
In general you want properties to be created with the this. syntax, so they're not shared, and functions to be created using the prototype syntax (there's no point in many identical functions)
You can run into trouble if you put functions on the prototypes. With primitives you won't notice the difference, since writing to them will write to the local object and ignore the protoype, but you can cause problems with arrays like this.
function FooController (){
this.foo = function () {
alert('foo');
}
}
FooController.prototype.bar = [];
var a = new FooController();
var b = new FooController();
a.bar.push['hi'];
alert(b.bar.length); //1
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.
I can define private member fields in module pattern using the code below
var myClass = function(){
var private_field1,private_field_2;
var private_func1 = function(){
//.......
}
//.........
var myObj = {
global_field1:2,
global_field2:"something",
global_func: function(){//......}
}
return myObj;
};
var obj = myClass();
This method works just fine, but the problem with this problem is that whenever I create a new object the copy of all the functions is created and loaded in memory (not like java where all objects of same class share same function memory)
I tried to use other method below:
var myClass = (function(){
var private_field1,private_field_2;//private static fields
var private_func1 = function(){
//.......
}
//.........
var Constr = function(){
//do something
}
Constr.prototype = {
//................
global_func: function(){//......}
}
return Constr;
}());
var obj1 = new myClass();
var obj2 = new myClass();
But the problem with this method is that obviously obj1,obj2 share same copy of private fields(so effectively they are static). So is there a way to define private fields in module pattern while using same copy of functions for the objects?
And for inheritance for the first method mentioned above, i first need to create a object inside the child class and then return that object.
var ChildClass = function(){
var childobj = myClass();
//override or add functions to childobj
return childobj ;
}
But this is effectively just wrapping the object of baseClass in childClass, Is there some other way to implement the same(for 1st or 2nd method) so that it can act like true java inheritance with protected, private, etc methods?
No. Privateness in JavaScript can only be done by scoping (and exporting from them: closures).
Those functions that need to access the private variables (and functions), called privileged methods need to be defined inside the constructor. Those methods that don't (which only interact with public properties or other methods) should be defined on the prototype object, so you will get a mixed approach in the end. Potentially combined with the static values you just discovered.
Btw, not the function [code] itself is copied and memorized multiple times. Only different scope objects (lexical environments) need to be stored.
Inheritance is usually not done by creating parent objects and extending them, but by creating child instances and extending them like a parent. This is can be done by applying the parent's constructor on the newly created child:
function ChildClass() {
ParentClass.call(this, /* … arguments */);
// usual body, using "this"
}
Also, the prototype of the Child inherits directly from the Parent's prototype object. This can be done via Object.create (needs to be shimmed for legacy browsers):
ChildClass.prototype = Object.create(ParentClass.prototype, {
constructor: {value:ChildClass}
});
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.