One interviewer asked me to explain what is this represented for in the following codes.
I had no idea about that.
Because I have not seen any codes like that before.
Please tell me is there any difference between these two and in what conditions such codes are useful?
function A(){
this.x=1;//No.1
function B(){
this.y=2;//No.2
}
}
I only know that when I use new to create a new object ,it has a property x equals to 1;
That depends on how you call the function. If you call it as a regular function, like this:
then
thiswill be thewindowobject of the document.If you use the function as an object constructor, like this:
then
thiswill be a reference to the newly created object.The reference
thisin theBfunction will never be anything, as it’s not possible to call the function. It’s local inside theAfunction and as there is no code in theAfunction that could be use to call theBfunction, it will never be called.If we make it possible to call the
Bfunction, the same thing applies as with theAfunction. Whatthisis depends on how you use the function. Even if you call theBfunction from within theAfunction when theAfunction is used as a constructor (and thusthisis an object reference inA), theBfunction doesn’t inheritthisfromA. It’s either a reference towindow(whenBis used as a function) or a reference to a newly created object (ifBis used as a constructor).