Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement inheritance in javascript?

How do I implement inheritence in Javascript? I am getting started with Knockout.js and implementing ViewModels/page. However I have some functions/code that I want it shared across all ViewModels.

I was wondering how do I implement inheritence in this case?

like image 253
Tim Tom Avatar asked Feb 21 '23 08:02

Tim Tom


1 Answers

Inheritance might not necessarily be the answer. Why not create an object literal with all the methods that each ViewModel should implement. I am unfamiliar with knockout, but here's how you might do it in native js.

    var sharedMethods = {
             run: function () {},
             jump: function () {}
        };

    function Person () {};
    // Use jQuery's extend method
    // Now person has run, jump, and talk
    $.extend(Person.prototype, sharedMethods, {
        talk: function () {}
    });
like image 168
Trevor Avatar answered Feb 22 '23 20:02

Trevor