this binding with a function wrapper.
by lid0
JavaScript
/**
This is a Simple program that shows how wrapping a function of an object behave in regards to "this" binding
Box
open()
preOpen()
BiggerBox()
initialzation
openSmallBox()
When initialzing an instance of BiggerBox, it will create a child instance of Box.
it will wrap the child instance open() method with an anonymus function, that
will trace some information and then call the original method that it save
in a temporary variable.
Observation:
calling openSmallBox() on the BiggerBox instance, will call our wrapper
the wrapper this binding is to Box instance, when the wrapper call the old method
the old method this is binded to the window global object.
To fix the binding we simply call the old method differently
from
old()
to
old.apply(this,[arg]);
See Console for trace messages
**/
var Box = function (){
this.open = function (){
console.log("Box::Open",this);
if (this === window){
console.error("this does not reference Box(this)");
}
}
this.preOpen = function(){
console.log("pre open");
this.open();
}
}
var BiggerBox = function (){
//on initialization
var b1 = new Box();
var old = b1.open;
this.BIGGER_BOX = function(){};
b1.open = function(f){
console.log("Box::Open(2)",this);
old(); //Option 1
//old.apply(this,[f]); //option 2 Fix
}
//public
this.openSmallBox = function (){
console.log("BigBox:Open()",this);
b1.open();
}
}
var Bb = new BiggerBox();
Bb.openSmallBox();
//--------------------
/*
var b1 = new Box();
var old = b1.open;
b1.open = function(f){
console.log("Box::Open(2)",this);
old.apply(this,[f]);
//var old_bind = old.bind(this).apply();
//old_bind()
}
b1.preOpen("Hi");
*/