HTMLElement.prototype.a = { a1: function(){ console.log(this) } }
will return Object {},
And I need HTMLElement.
How to be?
HTMLElement.prototype.a = { a1: function(){ console.log(this) } }
will return Object {},
And I need HTMLElement.
How to be?
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.
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 - Kirpich643document.querySelector
function? - GrundyIf 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.
Source: https://ru.stackoverflow.com/questions/501156/
All Articles
.a
object, but if you can’t do that, you can explicitly set the necessary context via.bind()
,.call()
orapply()
- NumminorihSFthis
- Grundy