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 object
Foo();
<= 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 argument
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…