HTMLElement.prototype.a = { a1: function(){ console.log(this) } } 

will return Object {},
And I need HTMLElement.

How to be?

  • expand the .a object, but if you can’t do that, you can explicitly set the necessary context via .bind() , .call() or apply() - NumminorihSF
  • How is this function called? Generally speaking, the context is not lost here, you have an object, a function is called for it, it is quite logical that this object is shown as this - Grundy

2 answers 2

In this case, the context is not lost.

you have an object

 { a1: function(){ console.log(this) } } 

the function is called, it is quite logical that this object is shown in the form of this .

If you need an HTMLElement , get the function straight to the prototype.

 HTMLElement.prototype.a = function(){ console.log(this); } 

But extending standard prototypes is not a good idea, especially DOM element prototypes.

  • 1) HTMLElement.prototype.a = function () {console.log (this); } - Thanks cap 2) "But extending standard prototypes is not a good idea, especially DOM element prototypes." - Why? - Kirpich643
  • @ Kirpich643, for example - Grundy
  • and then what to do? How to implement convenient work with one node? var $ = function (selector) { var node = function () { }; node.prototype = document.querySelector( selector ); return new node(); }; - $ ("body"). innerHTML VM100: 2 Uncaught TypeError: Illegal invocation (...) Nothing else comes to mind - Kirpich643
  • @ Kirpich643, why did not the jQuery approach please you? besides, it is not clear what exactly you are trying to do in the end - Grundy
  • @ Kirpich643, and also it is not clear what is the meaning of doing an intermediate function, if you can work with the result of the document.querySelector function? - Grundy

If you need an HTMLElement instance (and all functions in the prototype, through this , as a rule, they will refer to the instance instance), then there is also a specific variant of the form:

 var innerObject = { a1: function(){ console.log(this); } }; Object.defineProperty(HTMLElement.prototype, "a", { get: function () { return Object.keys(innerObject).reduce(function(res, key){ res[key] = innerObject[key].bind(this); return res; }.bind(this), {}); } }); 

But overall, this is not the best option to use. First of all for the reasons named @Grundy.