JavaScript functions, objects, prototypes, why they are used for, How to create an object, the ridiculous word ‘prototype’ etc, all of this we’ll try overviewing in this article.
What are functions and objects in JavaScript?
In JavaScript, we could define by using function definition both functions and objects. All of this depends on how we will make initialization of variables. If we use ‘new’ keyword our variable is an object, without it will be a function calls.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
var math = function Math(a, b){ this.a = a; this.b = b; this.sum = function(){ return a + b; } return a + b; // this is used when we call it as a function } var obj1 = math(10, 20); var obj2 = new math(10, 20); console.log(obj1); // 30 console.log(obj2); // Math { a: 10, b: 20, sum: [Function] } console.log(obj2.sum); // 30 // we can specify an object without a constructor by using {} obj3 = { a: 10, b: 20, sum: function(){ return this.a + this.b; } } console.log(obj3); // { a: 10, b: 20, sum: [Function: sum] } console.log(obj3.sum); // 30 |
As we can see they are the same. This very confuses newbies.
What is a prototype in JavaScript?
In JavaScript not exists classes. For add methods and properties from one object to other, it uses prototype properties. We can merge two objects. Suppose we have an object Animal and we want to add properties from this object to Dog or Cat. for this we use prototype and this syntax Dog.prototype = new Animal(). Using prototype we can assign any functions or variable to an object using Dog.prototype.[name] = [any function or variable]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var Animal = function Animal(food, motion){ this.eat = food || 'food'; this.motion = motion || 'walk'; this.print = function() { return 'Hello world!'; } } var Dog = function Dog(){ this.voice = 'bark'; } Dog.prototype = new Animal('meat'); // put prototype Animal to prototype Dog overwrite food Dog.prototype.say_something = function say_something(){ return 'woof woof'; } // add to prototype dog function var dog = new Dog console.log(dog.eat); // meat console.log(dog.motion); // walk console.log(dog.print()); // Hello world! console.log(dog.say_something()); // woof woof |