R
R
roskoshinsky2016-07-31 17:10:46
JavaScript
roskoshinsky, 2016-07-31 17:10:46

How to organize inheritance in JavaScript built-in classes so that methods are called up the chain?

Let's say the any() method is defined for the built-in Object and Array class through the prototype property:

Object.defineProperty(Object.prototype, "any", {
   value: function(){
      console.log("object.any");
      return this;
   } // function
   ,enumerable :false
});

Array.prototype.any = function(){
   console.log("array.any");
   return this;
}; // any

[].any();

However, when [].any() is called, the any() method defined for the Object class is called. What should be the scheme for defining methods so that functions are called up the chain depending on the presence of their closest parents in the prototypes?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
napa3um, 2016-07-31
@roskoshinsky

Object.prototype.any = function() {
   console.log('object.any');
   return this;
};

Array.prototype.any = function() {
   console.log('array.any');
   return this;
};

// или -----------------------------------------------

Object.defineProperty(Object.prototype, 'any', {
   value: function() {
      console.log('object.any');
      return this;
   },
   enumerable: false,
   writable: true // for assigment operation (=) support
});

Array.prototype.any = function() {
   console.log('array.any');
   return this;
};

// или -----------------------------------------------

Object.defineProperty(Object.prototype, 'any', {
   value: function() {
      console.log('object.any');
      return this;
   },
   enumerable: false
});

Object.defineProperty(Array.prototype, 'any', {
   value: function() {
      console.log('array.any');
      return this;
   },
   enumerable: false
});

// ---------------------------------------------------

[].any(); // array.any
({}).any(); // object.any

D
Dark Hole, 2016-07-31
@abyrkov

No hands?
Array.prototype.any.apply(this, arguments);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question