Klassen und Objekte in JavaScript: Unterschied zwischen den Versionen
Aus Wikizone
| Zeile 18: | Zeile 18: | ||
this.config = initObj.config | this.config = initObj.config | ||
this.otherstuff = initObj.otherstuff | this.otherstuff = initObj.otherstuff | ||
| + | }; | ||
| + | </pre> | ||
| + | |||
| + | === Kindklasse === | ||
| + | <pre> | ||
| + | // Define the Student constructor as child of Person | ||
| + | function Student(firstName, subject) { | ||
| + | // Call the parent constructor, making sure (using Function#call) | ||
| + | // that "this" is set correctly during the call | ||
| + | Person.call(this, firstName); | ||
| + | |||
| + | // Initialize our Student-specific properties | ||
| + | this.subject = subject; | ||
}; | }; | ||
</pre> | </pre> | ||
Version vom 5. Dezember 2014, 15:43 Uhr
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Klassen in JavaScript
In JS gibt es kein class Schlüsselwort. Stattdessen nimmt man einfach eine Funktion:
var Person = function () {
console.log('instance created');
};
var person1 = new Person();
var person2 = new Person();
Klassen in eigenem Namespace
Beispiel:
var MyApp = MyApp || function(initObj){
this.config = initObj.config
this.otherstuff = initObj.otherstuff
};
Kindklasse
// Define the Student constructor as child of Person
function Student(firstName, subject) {
// Call the parent constructor, making sure (using Function#call)
// that "this" is set correctly during the call
Person.call(this, firstName);
// Initialize our Student-specific properties
this.subject = subject;
};
Eigenschaften in Klassen
var Person = function (firstName) {
this.firstName = firstName;
console.log('Person instantiated');
};
var person1 = new Person('Alice');
var person2 = new Person('Bob');
// Show the firstName properties of the objects
console.log('person1 is ' + person1.firstName); // logs "person1 is Alice"
console.log('person2 is ' + person2.firstName); // logs "person2 is Bob"
Methoden in Klassen
Mit dem Schlüsselwort prototype kann man Funktionen zur Klasse hinzufügen.
var Person = function (firstName) {
this.firstName = firstName;
};
Person.prototype.sayHello = function() {
console.log("Hello, I'm " + this.firstName);
};
var person1 = new Person("Alice");
var person2 = new Person("Bob");
// call the Person sayHello method.
person1.sayHello(); // logs "Hello, I'm Alice"
person2.sayHello(); // logs "Hello, I'm Bob"
Die Methode ist ein