Stefan Muenz: JavaScript Methoden bei eigenen Objekten

Beitrag lesen

Hallo Michael,

ich habe nicht ganz verstanden, ob bei selbstdefinierten Javascript-Objekten auch Methoden definiert werden können oder nicht.

Das geht. Ich bin mal so frei und gebe dazu einfach die entsprechende Passage aus der JavaScript-Doku von Netscape wieder:

A method is a function associated with an object. You define a method the same way you define a standard function. Then you use the following syntax to associate the function with an existing object:

object.methodname = function_name

where object is an existing object, methodname is the name you are assigning to the method, and function_name is the name of the function.
You can then call the method in the context of the object as follows:

object.methodname(params);

You can define methods for an object type by including a method definition in the object constructor function. For example, you could define a function that would format and display the properties of the previously-defined car objects; for example,

function displayCar() {          
var result = "A Beautiful " + this.year + " " + this.make + " " + this.model
pretty_print(result)
}

where pretty_print is the function (defined in "Functions") to display a horizontal rule and a string. Notice the use of this to refer to the object to which the method belongs.
You can make this function a method of car by adding the statement

this.displayCar = displayCar;

to the object definition. So, the full definition of car would now look like

function car(make, model, year, owner) {          
this.make = make
this.model = model
this.year = year
this.owner = owner
this.displayCar = displayCar
}
Then you can call the displayCar method for each of the objects as follows:

car1.displayCar()
car2.displayCar()

Hoffe Du kommst damit klar!

Viele Gruesse
  Stefan Muenz