Extending Objects and Custom Objects using .prototype


/ Published in: JavaScript
Save to your folder(s)

Extend a custom object, and a pre-defined object(e.g. string) using .prototype available in JS.


Copy this code and paste it in your HTML
  1. //Extending an existing object
  2. function yourMethod(){
  3. //statements
  4. }
  5. //Attach it to the String Object
  6. String.prototype.methodName=yourMethod;
  7. //Usage
  8. var myVariable = "My String Here!"
  9. myVariable.methodName();
  10.  
  11.  
  12. //Extending a custom object
  13. //Create custom object
  14. function myObject() {
  15. //statements
  16. }
  17. //Create custom method
  18. function customMethod(){
  19. //statements
  20. }
  21. //Create custom property
  22. function customProperty() {
  23. //statements
  24. }
  25.  
  26. //Attach the property and method
  27. myObject.prototype.methodName=customMethod;
  28. myObject.prototype.prpertyName=customProperty;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.