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 :: javascript Adding Element to the Inner Array 
Javascript :: javascript include too large or too small numbers 
Javascript :: javascript Symbols are not included in for...in Loop 
Javascript :: javascript rest parameter 
Javascript :: reading an array from python to js 
Javascript :: javascript Assign Default Values 
Javascript :: fetch second parameters 
Javascript :: javascript Assigning to a new property on a non-extensible object is not allowed 
Javascript :: javascript Number() Method Used on Dates 
Javascript :: react destructuring with rename 
Javascript :: graphql type schema 
Javascript :: dropzone sending event add additional data 
Javascript :: How to add pop-up confirmation in angular typescript. 
Javascript :: How to Update the Props of a Rendered Component in vue Testing Library 
Javascript :: set display size phaser 
Javascript :: phaser place items on circle 
Javascript :: phaser create animation without frame names 
Javascript :: javascript multiplication without operator 
Javascript :: remove text and keep div inside a div jquery 
Javascript :: get random hsl color js 
Javascript :: function Tom(a, b) { return a + b; } 
Javascript :: how to choose a weighted random array element in javascript 
Javascript :: js function expression 
Javascript :: js index of 
Javascript :: useselector 
Javascript :: react native smart splash screen 
Javascript :: react native scrollview item bottom 
Javascript :: interface in javascript 
Javascript :: what are the comparison operators in javascript 
Javascript :: sub function javascript 
ADD CONTENT
Topic
Content
Source link
Name
8+7 =