I know this can be cheated in some browsers by setting proto, but what is the best way to setup one literal to be the prototype for another?
So far I can only think of making a copy into a constructor. Is there a more efficient way?
var meths = {
// creates a constructor function populated with a shallow copy of child
// the prototype for the new instance is set to the parent.
extend : function(parent, child){
var F = function(){
for (var prop in child){
if (child.hasOwnProperty(prop)){
this[prop] = child[prop];
}
}
}
F.prototype = parent;
return new F();
},
bind : function(func, context){
return function(){
func.apply(context, arguments);
}
}
};
Test:
var timerTest = meths.extend( meths, {
bindFN : function(func, context){
return this.bind(func, context)
},
setTimer : function(){
var o = this, x = 0, timer;
var boundFN = o.bindFN(timerGo, this);
// a very simple setTimeout counter.
function timerGo(){
console.log(x++);
timer = setTimeout(boundFN, 500);
if (x > 5) { clearTimeout(timer); timer = null; }
}
boundFN();
}
});
console.log (timerTest);
timerTest.setTimer();
Thanks
RLM