PDA

View Full Version : JavaScript Constructor



kayut
05-21-2018, 12:17 PM
Hey,

The following two constructor functions do the same job. But what is the difference between them and which one is more recomended?

First function



// we define a constructor for Person objects
function Person(name, age, isDeveloper) {
this.name = name;
this.age = age;
this.isDeveloper = isDeveloper || false;

this.writesCode = function() {
console.log(this.isDeveloper? "This person does write code" : "This person does not write code");
}
}

var person1 = new Person("Bob", 38, true);
var person2 = new Person("Alice", 32);

// prints out: This person does write code
person1.writesCode();
// prints out: this person does not write code
person2.writesCode();


Second function


// we define a constructor for Person objects
function Person(name, age, isDeveloper) {
this.name = name;
this.age = age;
this.isDeveloper = isDeveloper || false;
}

// we extend the function's prototype
Person.prototype.writesCode = function() {
console.log(this.isDeveloper? "This person does write code" : "This person does not write code");
}

var person1 = new Person("Bob", 38, true);
var person2 = new Person("Alice", 32);

// prints out: This person does write code
person1.writesCode();
// prints out: this person does not write code
person2.writesCode();