Klassen und Objekte in JavaScript: Unterschied zwischen den Versionen
Aus Wikizone
| Zeile 10: | Zeile 10: | ||
var person1 = new Person(); | var person1 = new Person(); | ||
var person2 = new Person(); | var person2 = new Person(); | ||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
</pre> | </pre> | ||
| Zeile 31: | Zeile 22: | ||
// Initialize our Student-specific properties | // Initialize our Student-specific properties | ||
this.subject = subject; | this.subject = subject; | ||
| + | }; | ||
| + | </pre> | ||
| + | === Klassen in eigenem Namespace === | ||
| + | Beispiel: | ||
| + | <pre> | ||
| + | var MyApp = MyApp || function(initObj){ | ||
| + | this.config = initObj.config | ||
| + | this.otherstuff = initObj.otherstuff | ||
}; | }; | ||
</pre> | </pre> | ||
Version vom 5. Dezember 2014, 15:44 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();
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;
};
Klassen in eigenem Namespace
Beispiel:
var MyApp = MyApp || function(initObj){
this.config = initObj.config
this.otherstuff = initObj.otherstuff
};
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