0

Am just a beginner in JavaScript and I found this keyword really difficult to understand for me. I know this depends on how the function is invoked.

The code is .

MyClass = function() {
    this.element = $('#element');

    this.myValue = 'something';

    // some more code
}

MyClass.prototype.myfunc = function() {
    this.element.click(function() {

    });
}

new MyClass();

I just need to know what this denotes in this.element.click(function() {}

Does it denote Myclass? Please help me in understanding the use of this keyword in prototype functions in JavaScript.

8
  • Myclass is a constructor. When you create a new object from it using new, this refers to that new object. Commented Apr 11, 2014 at 9:34
  • Brother there are no more links to refer am not geting its informarion properly..:( Commented Apr 11, 2014 at 9:34
  • You can check the right side(Related column) of this particular question. stackoverflow.com/questions/310870/… Commented Apr 11, 2014 at 9:35
  • Using a debugger, setting a break point and examining the value will give empiric insight. For the theory read a good book on JavaScript. Commented Apr 11, 2014 at 9:36
  • jsbooks.revolunet.com Commented Apr 11, 2014 at 9:36

1 Answer 1

2

I just need to know what this denotes in this.element.click(function() {}

Most likely, it's the object created by a new MyClass() expression. When you do new MyClass(), the JavaScript engine creates a new object, assigns MyClass.prototype as the object's underlying prototype, and then calls MyClass with this pointing to the new object. It returns that object as the result of the expression:

var o = new MyClass();

At this point, if you do:

o.myfunc();

...then within myfunc, this will be equal to o.

this is a slippery concept in JavaScript, though, which is why I said "most likely" above. More (on my blog):

Sign up to request clarification or add additional context in comments.

3 Comments

so if i call var b = Myclass()..Then this keyword in the function will be b ..right ?
@user3517846: No, you need the new in there: var b = new MyClass(); Then, this will be b within the call, provided you call myfunc like this: b.myfunc();
Got it and thanks ..:D ..:D ..and this is applicable only in the case of prototypes right ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.