Prototype Inheritance - The Right Way

I looked at the fact that JavaScript inheritance is the correct prototype, according to Douglas Crockford: http://javascript.crockford.com/prototypal.html

He writes: "Therefore, instead of creating classes, you create prototype objects, and then use the object function to create new instances."

I realized that this is the way to do this:

var objA = {
    func_a : function() {
        alert('A');
    }
};

var objB = Object.create(objA);
objB.func_a = function() {
   alert('B');
}
objB.func_b = function() {
};


var objA_instance1 = Object.create(objA);
var objA_instance2 = Object.create(objA);
var objB_instance1 = Object.create(objB);
var objB_instance2 = Object.create(objB);
etc...

But does this mean that now there are four examples of func_a (since it is not part of objA.prototype, it is just "inside"), or do I not get it right?

Also, is there a way to get an overridden function of a function (e.g. calling objA.func_a inside objB.func_a)?

Thanks in advance.

+3
source share
2

prototype [[Prototype]] , (FF __proto__); using Object.create() , objA objB "", .

, , , objA.func_a call() (), ,

objB.func_a = function() {
    objA.func_a.call(this); // call overridden method with current `this`
};
+2

func_a, objA, Crockford Object.create (objA) :

console.log(objA_instance1.func_a == objA .func_a); // true
console.log(objA_instance2.func_a == objA .func_a); // true

func_a objA_instances , :

console.log(objA_instance1.hasOwnProperty('func_a')); // false
console.log(objA_instance2.hasOwnProperty('func_a')); // false
+3

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


All Articles