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
thisis 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, andthiswill reflect that new objectFoo();<= here, you’re calling the function as-is, andthiswill be the global object(!)var obj = { foo: Foo };<= here, you’re calling the function as a method ofobj.foo();
obj;thiswill beobjFoo.call(thisObject, arg1, arg2);<= here, you can specify the value ofthisin the first argumentFoo.apply(thisObject, [args]);<= here, you can specify the value ofthisin 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 withapply, you can pass an array containing all the arguments.Note that in my example 2 above, the function should have been called
fooinstead ofFoo. Since it’s impossible to know off-hand whether a function is supposed to be called withnewor not, the consensus is to start the function name with a capital letter if it’s a constructor (and should be used withnew); otherwise, it should start with lowercase.