JavaScript prototype object not working 3

Posted by Lloyd on May 15, 2010 at 2:46 pm

If you happen to be working on a custom object and using the prototype property of JavaScript to add custom methods but it doesn’t seem to work, the solution is simple, you just need to instantiate your custom object by using the new keyword so all the custom methods through the prototype object are added.

// Sample custom object
var CustomObject = function() {
	this.props = {
			property: 'value'
		}
}
 
CustomObject.prototype = {
	CustomMethod: function() {
		alert(this.props.property);
	}
}
// Instantiate the custom object
var foo = new CustomObject;
// Doing that enables you to do this
foo.CustomMethod(); // alerts 'value'
 
// will not work because the object is not created as a new instance
// prototype methods not yet added to CustomObject
CustomObject.CustomMethod();

HTH :)


^ Back to Top