logo
down
shadow

Confusion over Classical and Prototypal Inheritance Javascript


Confusion over Classical and Prototypal Inheritance Javascript

By : ioananv
Date : December 01 2020, 04:55 PM
it should still fix some issue First, to get it straight, Javascript only has prototypal inheritance. What you can do is simulate "classical" inheritance. The difference between the two boils down to the syntax with which objects are instantiated - "classical" inheritance uses the more familiar constructor functions and "new" operator, which hide the inherent prototypal nature of Javascript's object creation and inheritance properties.
Let's break down both cases a bit.
code :


Share : facebook icon twitter icon
Classical Vs prototypal inheritance

Classical Vs prototypal inheritance


By : Kosumosushi
Date : March 29 2020, 07:55 AM
This might help you Prototype-based inheritance is more flexible. Any existing object can become a class from which additional objects will be spawned. This is handy where your objects offer several sets of services and/or they undergo a lot of state transformation before your program arrives at the point where the inheritance is needed.
A broad-spectrum discussion of modeling approaches is available here: http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html
Benefits of prototypal inheritance over classical?

Benefits of prototypal inheritance over classical?


By : user1979103
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I know that this answer is 3 years late but I really think the current answers do not provide enough information about how prototypal inheritance is better than classical inheritance.
First let's see the most common arguments JavaScript programmers state in defence of prototypal inheritance (I'm taking these arguments from the current pool of answers):
code :
var circle = {
    radius: 5
};
circle.area = function () {
    var radius = this.radius;
    return Math.PI * radius * radius;
};

circle.circumference = function () {
    return 2 * Math.PI * this.radius;
};
var circle2 = {
    radius: 10,
    area: circle.area,
    circumference: circle.circumference
};
var circle2 = Object.create(circle);
circle2.radius = 10;
function createCircle(radius) {
    var newCircle = Object.create(circle);
    newCircle.radius = radius;
    return newCircle;
}

var circle2 = createCircle(10);
var circle = {
    radius: 5,
    create: function (radius) {
        var circle = Object.create(this);
        circle.radius = radius;
        return circle;
    },
    area: function () {
        var radius = this.radius;
        return Math.PI * radius * radius;
    },
    circumference: function () {
        return 2 * Math.PI * this.radius;
    }
};

var circle2 = circle.create(10);
function Circle(radius) {
    this.radius = radius;
}

Circle.prototype.area = function () {
    var radius = this.radius;
    return Math.PI * radius * radius;
};

Circle.prototype.circumference = function () {         
    return 2 * Math.PI * this.radius;
};

var circle = new Circle(5);
var circle2 = new Circle(10);
function copyOf(object, prototype) {
    var prototypes = object.prototypes;
    var prototypeOf = Object.isPrototypeOf;
    return prototypes.indexOf(prototype) >= 0 ||
        prototypes.some(prototypeOf, prototype);
}
classical inheritance vs prototypal inheritance in javascript

classical inheritance vs prototypal inheritance in javascript


By : Michael Bernheiden
Date : March 29 2020, 07:55 AM
I wish this helpful for you Both the code samples you demonstrated in your question make use of prototypal inheritance. In fact any object-oriented code you write in JavaScript is a paradigm of prototypal inheritance. JavaScript simply doesn't have classical inheritance. This should clear things up a bit:
code :
                                   Inheritance
                                        |
                         +-----------------------------+
                         |                             |
                         v                             v
                    Prototypal                     Classical
                         |
         +------------------------------+
         |                              |
         v                              v
Prototypal Pattern             Constructor Pattern
                   Bike
                     |
    +---------------------------------+
    |                                 |
    v                                 v
Mud Bike                       Harley Davidson
+----------------------+----------------+---------------------------------------+
| Level of Abstraction | Name of Entity |                Comments               |
+----------------------+----------------+---------------------------------------+
| 0                    | John Doe       | Real World Entity.                    |
| 1                    | johnDoe        | Variable holding object.              |
| 2                    | Man            | Class of object johnDoe.              |
| 3                    | Human          | Superclass of class Man.              |
+----------------------+----------------+---------------------------------------+
class Human {
    // ...
}

class Man extends Human {
    // ...
}

Man johnDoe = new Man();
+----------------------+----------------+---------------------------------------+
| Level of Abstraction | Name of Entity |                Comments               |
+----------------------+----------------+---------------------------------------+
| 0                    | John Doe       | Real World Entity.                    |
| 1                    | johnDoe        | Variable holding object.              |
| 2                    | man            | Prototype of object johnDoe.          |
| 3                    | human          | Prototype of object man.              |
+----------------------+----------------+---------------------------------------+
var human = {};
var man = Object.create(human);
var johnDoe = Object.create(man);
function CLASS(base, body) {
    if (arguments.length < 2) body = base, base = Object.prototype;
    var prototype = Object.create(base, {new: {value: create}});
    return body.call(prototype, base), prototype;

    function create() {
        var self = Object.create(prototype);
        return prototype.hasOwnProperty("constructor") &&
            prototype.constructor.apply(self, arguments), self;
    }
}
var Human = CLASS(function () {
    var milliseconds = 1
      , seconds      = 1000 * milliseconds
      , minutes      = 60 * seconds
      , hours        = 60 * minutes
      , days         = 24 * hours
      , years        = 365.2425 * days;

    this.constructor = function (name, sex, dob) {
        this.name = name;
        this.sex = sex;
        this.dob = dob;
    };

    this.age = function () {
        return Math.floor((new Date - this.dob) / years);
    };
});

var Man = CLASS(Human, function (Human) {
    this.constructor = function (name, dob) {
        Human.constructor.call(this, name, "male", dob);
        if (this.age() < 18) throw new Error(name + " is a boy, not a man!");
    };
});

var johnDoe = Man.new("John Doe", new Date(1970, 0, 1));
Understanding why true prototypal inheritance is better than classical/pseudo prototypal inheritance and why i shouldn't

Understanding why true prototypal inheritance is better than classical/pseudo prototypal inheritance and why i shouldn't


By : TommySpaz
Date : March 29 2020, 07:55 AM
With these it helps Similar questions have been asked and answered many times before. See:
Constructor function vs Factory functions Classical Vs prototypal inheritance
code :
var Animal = function Animal(name) {
  this.name = name;
};

Animal.prototype.walk = function walk() {
  console.log(this.name + ' goes for a walk.');
};

var Rabbit = function Rabbit(/* name */) {
  // Because construction and instantiation are conflated, you must call super().
  Animal.prototype.constructor.apply(this, arguments);
};

// Classical inheritance is really built on top of prototypal inheritance:
Rabbit.prototype = Object.create(Animal.prototype);

// Fix the .constructor property:
Rabbit.prototype.constructor = Rabbit;

Rabbit.prototype.jump = function jump() {
  console.log(this.name + ' hops around a bit.');
};

var myRabbit = new Rabbit('Bunny George');

myRabbit.walk();
// Bunny George goes for a walk.
var animalMethods =  {
  walk: function walk() {
    console.log(this.name + ' goes for a walk.');
  }
};

var animal = function animal(name) {
  var instance = Object.create(animalMethods);
  instance.name = name;
  return instance;
};

var rabbitMethods = {
  jump: function jump() {
    console.log(this.name + ' hops around a bit.');
  }
};

var rabbit = function rabbit(name) {
  var proto = rabbitMethods;

  // This is more commonly done like mixin({}, animalMethods, rabbitMethods);
  // where mixin = $.extend, _.extend, mout.object.mixIn, etc... It just copies
  // source properties to the destination object (first arg), where properties from
  // the last argument override properties from previous source arguments.
  proto.walk = animalMethods.walk;
  var instance = Object.create(rabbitMethods);

  // This could just as easily be a functional mixin,
  // shared with both animal and rabbit.
  instance.name = name;
  return instance;
};

var rabbit2 = rabbit('Bunny Bob');

rabbit2.walk();
// Bunny Bob goes for a walk.
javascript pseudo classical inheritance and prototypal inheritance example confusion

javascript pseudo classical inheritance and prototypal inheritance example confusion


By : Gil Viernes Marcelo
Date : March 29 2020, 07:55 AM
this will help You are defining the canwalk property on the object prototype level that's why at the time when you instantiate the object you get true on alerting (animal.canWalk). The reason why on the second alert you got false is that meantime you call the sit function where you set canWalk as false.
That's why is not too good practice to follow strictly the prototypal inheritance pattern: typically, instances want to have their own copies of all properties. This is why the prototype pattern is rarely used on its own.
code :
function SuperType(name){
    this.name = name;
    this.colors = ["red", "blue", "green"];
}

SuperType.prototype.sayName = function(){
    alert(this.name);
};

function SubType(name, age){
    SuperType.call(this, name); //second call to SuperType()

    this.age = age;
}

SubType.prototype = new SuperType(); //first call to SuperType()
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
    alert(this.age);
};
function inheritPrototype(subType, superType){
    var prototype = object(superType.prototype); //create object
    prototype.constructor = subType; //augment object
    subType.prototype = prototype; //assign object
}
SubType.prototype = new SuperType(); //first call to SuperType()
SubType.prototype.constructor = SubType;
inheritPrototype(SubType, SuperType);
function SuperType(name){
    this.name = name;
    this.colors = ["red", "blue", "green"];
}

SuperType.prototype = {
    constructor: SuperType,
    sayName : function() {
        alert(this.name);
    }
}
var superType = new SuperType();
alert(superType instanceof Object); //true
alert(superType instanceof SuperType); //true
alert(superType.constructor == Person); //false
alert(superType.constructor == SuperType); //true
function SuperType() {
    this.property = true;
}

SuperType.prototype.getSuperValue = function() {
    return this.property;
};

function SubType() {
    this.subproperty = false;
}

//inherit from SuperType
SubType.prototype = new SuperType();

SubType.prototype.getSubValue = function () {
    return this.subproperty;
};

//override existing method
SubType.prototype.getSuperValue = function () {
    return false;
};
Related Posts Related Posts :
  • angular 6 Please add a @NgModule annotation
  • Trying to cast element ID to class selector in jQuery
  • Swipe JS - Display 3 Slides at a time
  • Jasmine test to call function when value is null
  • Redux reducer gets string instead of object
  • Keep chrome javascript running even if page reload
  • The event.target.value is not insert the userinput into a variable
  • Exporting HTML tables to Excel (.xls) in a separate sheet
  • Jquery tooltip on dialog close button
  • access variable inside anonymous function from outside
  • How come func is called from a function?
  • How to change add and remove active class in JavaScript
  • how to toggle a specific div in javascript
  • How to get all the values from multiple keys of an array of object?
  • jQuery bind() unbind() and on() and off()
  • regular expression to find DD Month YYYY from a string
  • How to upload files from web client (HTML/jQuery form) to your Dropbox folder
  • Backbone history and require.js issue
  • How to take screen shot of current webpage using Javascript/JQuery?
  • Store meridiem in a variable
  • class declared inside closure vs standard class without closure
  • javascript confirm box always return true
  • dynamically changing the size of font size based on text length using css and html
  • Node.js - Getting the host IP address while on Amazon EC2
  • Confusing CSS, can anyone explain please
  • How to install v8-profiler on Windows 8 (64 bit) using npm?
  • Resolve promise based on another promise
  • google maps adding overlay layer above UI and markers
  • Style specific letter?
  • RangeError: Maximum call stack size exceeded with array.slice
  • node rest client get with local variable
  • If condition not executes while mouse move fastly
  • Count the number of displayed elements in a HTML list
  • Locate JavaScript source code in Emacs
  • Clean, Modular Code vs MV* Frameworks
  • infinite scroll without loading image
  • Backbone: reverse collection order with comparator
  • What do printers ignore?
  • jQuery UI .tabs() Contentless tab?
  • Execute Javascript alert() after page (visually) loaded
  • JavaScript - duplicating array doesn't work
  • Excessive clickable area below image
  • JavaScript Regex: Replace |b| with <b>
  • Unexpected value change in 2D array in JavaScript
  • Function doesnt see parameter as a array of objects
  • jQuery fetch keypress event on chrome and IE
  • How to enable jquery validate localization?
  • Cassandra map collection returned by node.js Helenus looks odd
  • angular ng-repeat with multiple filter options
  • Selecting Children without ID or Class names
  • How to uncheck a group of checkboxes when another checkbox is checked
  • Is hiding content by Javascript or jQuery Worth trying
  • Load XUL resource using javascript
  • XML to HTML text area from server file system
  • set focus() on textbox on form onload
  • es lint '' is assigned a value but never used' eventhough i have used it
  • Can "name" attribute be used for custom VueJS components
  • Get innerHTML of content when it is clicked
  • HTTPS causes CSS animations to not load? Very confused
  • How to hide other div apart from touched div to the band
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org