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?
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
:
new Foo();
<= here, you’re creating a new object, and this
will reflect that new objectFoo();
<= here, you're calling the function as-is, and this
will be the global object(!)var obj = { foo: Foo };
obj.foo();
<= here, you're calling the function as a method of obj
; this
will be obj
Foo.call(thisObject, arg1, arg2);
<= here, you can specify the value of this
in the first argumentFoo.apply(thisObject, [args]);
<= here, you can specify the value of this
in the first argumentIn 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.
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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With