How to implement inheritance in javascript?

How to implement inheritance in javascript? I start working with Knockout.js and implement ViewModels / page. However, I have some functions / code that I want it to be shared in all ViewModels.

I was wondering how to implement inheritance in this case?

+4
source share
3 answers

Inheritance may not necessarily be the answer. Why not create an object literal with all the methods that every ViewModel should implement. I am not familiar with knockout, but here is how you can do it in native js.

var sharedMethods = { run: function () {}, jump: function () {} }; function Person () {}; // Use jQuery extend method // Now person has run, jump, and talk $.extend(Person.prototype, sharedMethods, { talk: function () {} }); 
+6
source

JavaScript provides prototype inheritance. Objects inherit from other objects. This may be good for method inheritance, but it does not work for property inheritance.

Usually for method inheritance you can use:

 function BaseViewModel() { var self = this; self.name = ko.observable(); } function Person() { var self = this; self.firstname = ko.observable(); } Person.prototype = new BaseViewModel(); 

But it makes all people share the same object as the prototype! When you change the name for one person, the meaning applies to all Persons. I usually use the jQuery expand method.

 function Person() { var self = this; $.extend(self, new BaseViewModel()); self.firstname = ko.observable(); 

}

Thus, the values ​​from BaseViewModel will be copied to Person.

+2
source

Here is the link from crockford.com
This is the best place to know anything about object oriented Javascript.
Although his methods are not difficult to understand at first. Its one of the best best resources because it is best known for its continued involvement in the development of the JavaScript language, the popularization of the JSON (JavaScript Object Notation) data format, and the development of various JavaScript-related tools such as JSLint and JSMin.

0
source

Source: https://habr.com/ru/post/1414605/


All Articles