1

Learning JavaScript OOP ... And being all day on that field but...
I cannot understand / find how to create custom JS Method just like

.toString() , .toUpperCase() ...and other methods, that for e.g. if you have an accessed object like

customer.name // John 

and you use:

customer.name.toLowerCase();

will give you // john

That means that a function Method toLowerCase() somehow uses the this reference of the prefixed object as the operable argument for the return operation.

How to do something like that? Attach a method that will do some stuff with some unknown previous object?

OK, just a stupid example, let's say we want to be able to create a .addLength() Method that will simply allow us to do: customer.name.addLength() // John Name length = 4

function addLength(){   
    var that = this;
    var name = that.toString();
    return ( name +' Name length = '+ name.length );   
}

ok, this is totally wrong I know, it was just to describe somehow.
It's not for a purpose, just to understand. (better useful examples are welcome) Thanks!

Ginnani
  • 325
  • 1
  • 5
  • 19

1 Answers1

1

You want to make use of protoypal inheritance

https://stackoverflow.com/a/572996

http://javascript.crockford.com/prototypal.html

Community
  • 1
  • 1
Zack Burt
  • 8,257
  • 10
  • 53
  • 81
  • But how can I access an object prototype if I don't know anything about the previous object? I just want to create a `.addLength()` Method for some **unknown** prefixed object. Just like normal JS methods. I'm a bit lost. Thanks – Ginnani Jan 26 '13 at 06:12
  • Object.prototype.addLength = function() { return this.length; } ---- this will add the addLength method to the prototype of the Object object..which every new object will refer to..read the links I posted - especially the one on prototypal inheritance – Zack Burt Jan 26 '13 at 06:19