-1

I'm new to JavaScript so I apologize if it's too dumb question.I don't understand how this keyword behaves in examples below.

In first case, this refers to window object:

Element.prototype.x = this;
some_element.x; // Returns window object.

And in second, it refers to DOM Element:

Element.prototype.x = function(){return this;};
some_element.x(); // Returns element itself.

Why? How do those examples differ?

Jay Sky
  • 93
  • 1
  • 8

1 Answers1

0

In first case, this refers to window object:

Element.prototype.x = this; ( Here the scope points to window "Global scope in js" )

And in second, it refers to DOM Element:

Element.prototype.x = function(){return this;}; ( But where as here You are defining a function to the Object "Element", so the scope of this keyword is pointing "Element" Object. )

Bala.Raj
  • 581
  • 3
  • 15