Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.javascript > #26471
| From | "Tony Johansson" <johansson.andersson@telia.com> |
|---|---|
| Newsgroups | comp.lang.javascript |
| Subject | Why use prototype in this example |
| Date | 2015-01-06 23:29 +0100 |
| Organization | A noiseless patient Spider |
| Message-ID | <m8hnjv$d29$1@dont-email.me> (permalink) |
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
Back to comp.lang.javascript | Previous | Next — Next in thread | Find similar | Unroll thread
Why use prototype in this example "Tony Johansson" <johansson.andersson@telia.com> - 2015-01-06 23:29 +0100 Re: Why use prototype in this example "Christoph M. Becker" <cmbecker69@arcor.de> - 2015-01-06 23:53 +0100 Re: Why use prototype in this example Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-01-07 04:25 +0100
csiph-web