Tony Johansson
1/6/2015 10:30:00 PM
Here I have two examples. The difference between these is that in example 1
I create sayHello as a prototype while in
exemple 2 I add sayHello as a function in the class Person
I mean in both example 1 and 2 I create an instance of Person.
I can't see any point to use a prototype compared to add methods to the
class?
Start example 1 med prototype
***********************
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"
End example 1
************
Start example 2 utan prototype
***********************
var Person = function (firstName) {
this.firstName = firstName;
this.sayHello = function () {
alert("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"
//Tony