5

I get confused about 'this' keyword in the following codes, there are two 'this':

var Foo = function(string){
  this.name=string // 1st-this
}

Foo.prototype.get_name = function(){
  return this.name // 2nd-this
}

var myFoo = new Foo('John')

the_name=myFoo.get_name()

'the_name' is equal to 'John', the prototype method get the name by return this.name. But can anyone explain to me the 1st-this and 2nd-this, what do they stand for?

Aziz Shaikh
  • 15,104
  • 9
  • 55
  • 73
Mellon
  • 33,620
  • 73
  • 177
  • 259
  • See [how does the `this` keyword work in JavaScript?](http://stackoverflow.com/q/3127429/1048572) – Bergi Apr 18 '15 at 21:05

8 Answers8

15

In Javascript, the value of this is dependent on the way you call the function.

There are 5 ways to call a function in JS, and they all have effect on this:

  1. new Foo(); <= here, you’re creating a new object, and this will reflect that new object
  2. Foo(); <= here, you're calling the function as-is, and this will be the global object(!)
  3. var obj = { foo: Foo };
    obj.foo();
    <= here, you're calling the function as a method of obj; this will be obj
  4. Foo.call(thisObject, arg1, arg2); <= here, you can specify the value of this in the first argument
  5. Foo.apply(thisObject, [args]); <= here, you can specify the value of this in the first argument

In 4 and 5, the difference between call and apply is that with call, you need to pass all the arguments separately, whereas with apply, you can pass an array containing all the arguments.

Note that in my example 2 above, the function should have been called foo instead of Foo. Since it’s impossible to know off-hand whether a function is supposed to be called with new or not, the consensus is to start the function name with a capital letter if it’s a constructor (and should be used with new); otherwise, it should start with lowercase.

Martijn
  • 12,254
  • 3
  • 46
  • 58
2

this link make you understand : The this keyword

function doSomething() {
   this.style.color = '#cc0000';
}

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript. An onclick property, though, is owned by the HTML element it belongs to.

Pranay Rana
  • 164,177
  • 33
  • 228
  • 256
  • 2
    Imo is that the term "owner" is misleading. E.g. a function can be a property of more than just *one* object. But of course it cannot refer to both objects at the same time. – Felix Kling Mar 25 '11 at 07:54
2

The answer is "it depends", since the meaning of this depends on the context in which it is invoked.

For example in things like callbacks, this no longer refers to the current object, but more typically to the DOM element on which the event occurred:

So this identical-looking function:

Foo.prototype.handleSomeEvent = function(e) {
    return this.name;
}

if used as an event callback would try to resolve the name attribute of the element, and not your object's name.

Alnitak
  • 313,276
  • 69
  • 379
  • 466
2

When you use the new keyword this is the instance object that you are creating.

var foo = new Bar();

i.e. the instance of Bar being assigned to foo


When you don't, this is the object on which the method you are calling lives.

var baz = foo.thing();
var boz = thing();

i.e. foo in the first example and window in the second (window is the default object).


You can also fritz with it using apply

var baz = foo.thing.apply(bar);

Here this (still inside the thing method) is bar)

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • @Mellon: Bonus question for you (to see whether you really understood it ;)): What does `this` refer to in `get()`? `var get = myFoo.get_name; var name = get();` (`get_name` is the function you defined in your example). – Felix Kling Mar 25 '11 at 08:17
1

this refers to the object invoking the function, which in this case is myFoo. When you construct myFoo as a new Foo('John') the this keyword enables you to set myFoo.name = 'John', so when you call myFoo.get_name() it will also let you return myFoo.name which equals John.

mVChr
  • 46,510
  • 10
  • 101
  • 99
  • Thank you :), I more question, can I understand in the way that, prototype is the parent of myFoo (myFoo is the child of prototype)? – Mellon Mar 25 '11 at 07:45
  • The prototype contains properties and methods that all objects created with `new Foo()` share. So even though in `myFoo` you may override `get_name` with a function with the same name in that instance, another object `myOtherFoo` will keep `get_name` in its prototypal form. – mVChr Mar 25 '11 at 07:50
1

In your example they are the same, when you call this from a method you override in the prototype chain you are referring to the same thing as when calling this from within the constructor function.

It gets trickier when working with callbacks or when defining member variables in prototype methods.

ChrisR
  • 13,942
  • 13
  • 65
  • 105
  • Thank you :), I more question, can I understand in the way that, prototype is the parent of myFoo (myFoo is the child of prototype)? – Mellon Mar 25 '11 at 07:46
1

wow all of these different answers, and only one of them even used the word "context"! Here is the straightforward answer to your question:

the this keyword is an object reference that points to the context object.

In your example, this refers to an instance of the Foo object.

Eric Rowell
  • 5,039
  • 21
  • 22
0

The "this" keyword always refers to the owner of the function. So for instance if you click on a button that accesses that function, this refers to that button. So if you have button A that has an onclick that calls that function then this is A.

In this case this would be John since in both cases they reference myFoo which is John since Myfoo is used in calling them

StevenDStanton
  • 815
  • 7
  • 22