85220

Javascript inherit static and instance methods/properties

Question:

In javascript how would I set up inheritance so that <strong>static</strong> and <strong>instance</strong> properties/methods are inherited?

My goal is to build a base "class" that 3rd parties would inherit from, and be able to call static and instance properties/methods inherited from the base "class".

In my example I define a recipe base class that others can inherit from and create recipes off of:

Function.prototype.inherits = function (base) { // code to inherit instance and static // props/methods here var temp = function () { }; temp.prototype = base.prototype; this.prototype = new temp(); } function Recipe() { var self = this; Recipe.ingredients = { }; Recipe.prepare = function (ingredients) { // prepare each of the ingredients... var preparedIngredients = ingredients; Recipe.ingredients = preparedIngredients; }; self.share = function () { console.log('Recipe Shared!'); }; } Toast.inherits(Recipe); function Toast() { var self = this; } var toast = new Toast(); // Child function should inherit static methods Toast.Prepare({ bread: '2 slices', butter: '1 knob', jam: '1 tablespoon' }); // Child function should inherit static properties console.log(Toast.ingredients); // Child function should inherit instance methods as well toast.share(); // And if I define another it gets its own static properties/methods // Spaghetti.ingredients !== Toast.ingredients Spaghetti.inherits(Recipe); function Spaghetti() { var self = this; } Spaghetti.prepare({ noodles: '1 box', tomatoes: 2, sausage: 1 });

Plnkr here: <a href="http://plnkr.co/edit/x8rKeKXSxDHMB4CD6j1c" rel="nofollow">http://plnkr.co/edit/x8rKeKXSxDHMB4CD6j1c</a>

Answer1:

Your inheritance is wrong, Toast is not a Recipe it has a Recipe. Ingredients of Recipe cannot be static because a Recipe can be used for toast, pancake or many other dishes.

function Recipe(name,ingredients) { this.name=name; this.ingredients = ingredients; }; var Toast = function(){} Toast.prototype.recipe = new Recipe('toast',{ bread: '2 slices', butter: '1 knob', jam: '1 tablespoon' });

More info on prototype can be found here: <a href="https://stackoverflow.com/a/16063711/1641941" rel="nofollow">https://stackoverflow.com/a/16063711/1641941</a>

If you want to inherit static members you need a better example: for example MyDate and MyDateTime.

var MyDate=function(dateString){ this.date=(dateString)?new Date(dateString) :new Date(); }; MyDate.YEAR=Date.prototype.getFullYear; //... others like MONTH, DAY ... MyDate.prototype.get = function(what){ if(what && typeof what==='function'){ return what.call(this.date); } console.log('nope'); }; var MyDateTime=function(dateString){ MyDate.call(this,dateString); }; //set static properties (can write a function for this) for(mystatic in MyDate){ if(MyDate.hasOwnProperty(mystatic)){ MyDateTime[mystatic]=MyDate[mystatic]; } } MyDateTime.HOUR=Date.prototype.getHours; //instead of breaking encapsulation for inheritance // maybe just use Object.create and polyfil if needed // and stop reading DC when it comes to this subject MyDateTime.prototype=Object.create(MyDate.prototype); MyDateTime.prototype.constructor=MyDateTime; var d = new MyDate(); console.log(d.get(MyDate.YEAR)); var dt = new MyDateTime(); console.log(dt.get(MyDateTime.YEAR)); console.log(dt.get(MyDateTime.HOUR));

Answer2:

Here's an example of static/instance member inheritance. This is using small class framework I wrote to make oop in javascript easier to use and nicer to look at. It's <a href="https://github.com/digital-synapse/ds.oop" rel="nofollow">available on github</a> if you are interested.

var Base = new ds.class({ type: 'Base', constructor: function() { this.instanceprop: 'am i instance?' }, staticprop: 'am i static?' }); var Example = new ds.class({ type: 'Example', inherits: Base, constructor: function() {} }); var eb = new Base(); var ex = new Example(); console.log( Base.staticprop ); console.log( eb.instanceprop ); console.log( Example.staticprop ); console.log( ex.instanceprop );

Recommend

  • Bread-crumb style navigation for Winforms
  • How to make string to dictionary and update values that exist?
  • Creating dummy variables from multiple strings in the same row
  • Session Variable not working in Internet Explorer, but works fine in Firefox / Chrome
  • Prepared statement works for INSERT but not for SELECT
  • Recursive Hierarchical Joins with Depth
  • GIT or SVN or… for front-end developers
  • How to use MediaRecorder to capture video on Android?
  • How to make PDO query work inside a function
  • Why doesn't ASM call my ``visitCode``?
  • Reset MySqli pointer?
  • PDO & MS SQL Server: inserting value for integer column results in error
  • Psycopg2 string formatting with variable names for type creation
  • Git Staged - It have file history? [closed]
  • MySql “view”, “prepared statement” and “Prepared statement needs to be re-prepared”
  • To use other table as a WHERE criteria in SQL
  • Left Join connecting primary key to normal column causes havoc
  • how to get DAYS absent from working days from given date range?
  • Execute Success but num_rows return 0 [PHP-MySQL]
  • MySQLi using an IN in a where
  • Android: playing audio files in /res/raw by file name
  • Passing inputs to program prompt in a batch file
  • PHP PDO Update prepared statement problem
  • TelephonyManager crashing on android studio
  • Unable to retrieve number before incoming call in marshmallow
  • IllegalStateException “System services not available to Activities before onCreate()”
  • android.app.PendingIntent cannot be accessed ouside the package
  • Inserting NULL/empty string using libpqxx library
  • How to get the url of a file of google drive to download in android
  • Copying rows in a database when rows have children
  • Passing information to server-side function in a Google Docs Add On
  • event.getSource() returns null Accessibility in android
  • Loading Bitmap to ImageView from URL in android
  • Why doesnt this Java loop in a thread work?
  • How to Make a Spinner (In a Fragment) That Changes the App's Language?
  • Ubuntu and bcrypt
  • Unity3D & Android: Difference between “UnityMain” and “main” threads?
  • Xamarin Forms - UWP Fonts
  • Delete MySQLi record without showing the id in the URL
  • Angular 2 constructor injection vs direct access