Getting started with JavaScriptFunctionsArraysObjectsAJAXClassesArithmetic (Math)Comparison OperationsConditionsLoopsPromisesRegular expressionsDateError HandlingGeolocationCookiesIntervals and TimeoutsGeneratorsHistoryStrict modeCustom ElementsJSONBinary DataTemplate LiteralsWeb StorageFetchScopeModulesScreenInheritanceTimestampsDestructuring assignmentWorkersVariable coercion/conversionDebuggingNotifications APIBuilt-in ConstantsWebSocketsWeb Cryptography APIAsync functions (async/await)StringsConstructor functionsexecCommand and contenteditablePerformance TipsMapCreational Design PatternsrequestAnimationFrameReserved KeywordsMethod ChainingGlobal error handling in browsersUnary OperatorsFile API, Blobs and FileReadersCommentsConsoleTail Call OptimizationDetecting browserEnumerationsSymbolsLocalizationSelection APICallbacksSetDeclarations and AssignmentsFunctional JavaScriptModals - PromptsData attributesThe Event LoopBattery Status APIData ManipulationBitwise operatorsTranspilingBOM (Browser Object Model)Unit Testing JavascriptLinters - Ensuring code qualityAutomatic Semicolon Insertion - ASIIndexedDBAnti-patternsNavigator ObjectModularization TechniquesProxySame Origin Policy & Cross-Origin CommunicationArrow Functions.postMessage() and MessageEventWeakMapWeakSetEscape SequencesBehavioral Design PatternsServer-sent eventsAsync IteratorsNamespacingEvaluating JavaScriptMemory efficiencyDate ComparisonHow to make iterator usable inside async callback functionContext (this)Setters and GettersVibration APIPrototypes, objectsDatatypes in JavascriptBitwise Operators - Real World Examples (snippets)Fluent APITilde ~Security issuesUsing javascript to get/set CSS custom variablesJavaScript VariablesEvents

Prototypes, objects

Other topics

Creation and initialising Prototype

var Human = function() {
  this.canWalk = true;
  this.canSpeak = true; // 

};

Person.prototype.greet = function() {
  if (this.canSpeak) { // checks whether this prototype has instance of speak
    this.name = "Steve"
    console.log('Hi, I am ' + this.name);
  } else{
     console.log('Sorry i can not speak');
  }
};

The prototype can be instantiated like this

obj = Object.create(Person.prototype);
ob.greet();

We can pass value for the constructor and make the boolean true and false based on the requirement.

Detailed Explanation

var Human = function() {
    this.canSpeak = true;
};
// Basic greet function which will greet based on the canSpeak flag
Human.prototype.greet = function() {
    if (this.canSpeak) {
        console.log('Hi, I am ' + this.name);
    }
};

var Student = function(name, title) {
    Human.call(this); // Instantiating the Human object and getting the memebers of the class
    this.name = name; // inherting the name from the human class
    this.title = title; // getting the title from the called function
};

Student.prototype = Object.create(Human.prototype);
Student.prototype.constructor = Student;

Student.prototype.greet = function() {
    if (this.canSpeak) {
        console.log('Hi, I am ' + this.name + ', the ' + this.title);
    }
};

var Customer = function(name) {
    Human.call(this); // inherting from the base class
    this.name = name;
};

Customer.prototype = Object.create(Human.prototype); // creating the object
Customer.prototype.constructor = Customer;


var bill = new Student('Billy', 'Teacher');
var carter = new Customer('Carter');
var andy = new Student('Andy', 'Bill');
var virat = new Customer('Virat');

bill.greet();
// Hi, I am Bob, the Teacher

carter.greet();
// Hi, I am Carter

andy.greet();
// Hi, I am Andy, the Bill

virat.greet();

Contributors

Topic Id: 9586

Example Ids: 29606

This site is not affiliated with any of the contributors.