I asked a question on Javascript this points to Window object regarding “this” points to Window object.
here is source code
var archive = function(){}
archive.prototype.action = {
test: function(callback){
callback();
},
test2: function(){
console.log(this);
}
}
var oArchive = new archive();
oArchive.action.test(oArchive.action.test2);
Tim Down wrote “but that function is then called using callback(), which means it is not called as a method and hence this is the global object”.
What are differences between calling a function by its actual name and callback() as shown on the source code?
How does console.log(this) in test2 points to Window when it is inside archive.action???
In JavaScript you can invoke functions using 4 different invocation patterns:
The patterns mainly differ in how the
thisparameter is initialized.When you use
oArchive.action.test2(), you would be invoking thetest2()function with the method pattern, and in this casethiswould be bound to theactionobject. JavaScript will use the method pattern whenever the invocation expression contains a refinement (i.e. the.dot expression or the[subscript]expression).On the other hand, when a function is not the property of an object, then it is invoked using the function pattern. In this case, the
thisparameter is bound to the global object, and in fact this is how JavaScript is invoking yourcallback()function.Douglas Crockford in his Good Parts book, describes this as a mistake in the design of the language, and suggests some possible workarounds. In you case, one easy workaround would be to invoke the callback using
call()orapply(), as Tim Down suggested in your previous question:This works because the Apply/Call invocation pattern lets you choose the value of
this, which is what you require.