Skip to content

Instantly share code, notes, and snippets.

@r01010010
Last active August 29, 2015 14:12
Show Gist options
  • Save r01010010/1d8e22b86040012b5798 to your computer and use it in GitHub Desktop.
Save r01010010/1d8e22b86040012b5798 to your computer and use it in GitHub Desktop.
Preserve 'this' in prototype function
var EValidator = require('evalidator');
var mainObject = {
propertyObject: new PropertyObject(),
ev: new SuperEValidator()
};
/**
* EValidator extension object
* @constructor
*/
function SuperEValidator(){
// EValidator Inheritance
EValidator.apply(this, arguments);
}
SuperEValidator.prototype = Object.create(EValidator.prototype);
SuperEValidator.prototype.constructor = SuperEValidator;
SuperEValidator.prototype.method_A = function(){
console.log('method_A called');
};
SuperEValidator.prototype.method_B = function(){
this.method_A();
};
/**
* Plan object
* @constructor
*/
function PropertyObject(){}
PropertyObject.prototype.method_A = function(){
console.log('method_A called');
};
PropertyObject.prototype.method_B = function(){
this.method_A();
};
/*** Calling methods from MainObject ***/
mainObject.propertyObject.method_B(); // Throws Error 'MainObject doesn't have 'method_A' method
mainObject.ev.method_B(); // Throws Error 'MainObject doesn't have 'method_A' method
// Solutions:
// 1.- set var me; at global level and set it to 'this' at PropertyObject Constructor, then inside method_B use 'me' instead 'this'
// 2.- Inside method_B use 'PropertyObject.prototype' instead 'this'
// 3.- Any other one???
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment