Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript constructor and prototype


//Define the object specific properties inside the constructor
function Human(name, age){
	this.name = name,
	this.age = age,
	this.friends = ["Ali", "Shehzad"]
}
//Define the shared properties and methods using the prototype
Human.prototype.sayName = function(){
	console.log(this.name);
}
//Create two objects using the Human constructor function
var person1 = new Human("Mohtashim", 31);
var person2 = new Human("Fasih", 40);

//Lets check if person1 and person2 have points to the same instance of the sayName function
console.log(person1.sayName === person2.sayName) // true

//Let's modify friends property and check
person1.friends.push("Fasih");

console.log(person1.friends)// Output: "Ali, Shehzad, Fasih"
console.log(person2.friends)//Output: "Ali, Shehzad"
Comment

JavaScript Add Methods to a Constructor Function Using Prototype

// constructor function
function Person () {
    this.name = 'John',
    this.age = 23
}

// creating objects
const person1 = new Person();
const person2 = new Person();

// adding a method to the constructor function
Person.prototype.greet = function() {
    console.log('hello' + ' ' +  this.name);
}

person1.greet(); // hello John
person2.greet(); // hello John
Comment

PREVIOUS NEXT
Code Example
Javascript :: how to get the timestamp in javascript 
Javascript :: font awesome react native icons 
Javascript :: how to get key from a button in react 
Javascript :: How to hthe amount of users online in discordjs 
Javascript :: check if var is NaN 
Javascript :: electron disable menu 
Javascript :: number to word js 
Javascript :: create multiple collections in mongodb 
Javascript :: javascript style font size 
Javascript :: how to read json file in python stack overflow 
Javascript :: how to generate random id in javascript 
Javascript :: javascript dynamic import folder 
Javascript :: npm shrinkwrap primordials 
Javascript :: react transition group 
Javascript :: nodejs remove null from object 
Javascript :: javascript compare arrays 
Javascript :: ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @agm/core@1.1.0 npm ERR! Found: @angular/common@10.0.14 
Javascript :: js string times 
Javascript :: js check if string includes from array 
Javascript :: downgrade node version windows using npm 
Javascript :: javascript replace all spaces 
Javascript :: Count of positives / sum of negatives 
Javascript :: How to loop through an object in JavaScript with a for…in loop 
Javascript :: javascript break foreach 
Javascript :: javascript ternary 
Javascript :: retrieve data from option select js 
Javascript :: how to loop an object in javascript 
Javascript :: moment timezone set default timezone 
Javascript :: javascript to remove few items from array 
Javascript :: start date and end date validation antd 
ADD CONTENT
Topic
Content
Source link
Name
5+2 =