Last active
August 29, 2015 14:12
-
-
Save r01010010/1d8e22b86040012b5798 to your computer and use it in GitHub Desktop.
Preserve 'this' in prototype function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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