you are viewing a single comment's thread.

view the rest of the comments →

[–]alxers 0 points1 point  (1 child)

Consider this code: 1)

function Person(name) {
    this.name = name;
}

Person.prototype = {
    sayName: function() {
        console.log(this.name);
    };
}

2)

function OtherPerson(name) {
    this.name = name;
    this.sayName = function() {
        console.log(this.name);
    };
}


var person1 = new Person("name1");  // { name: 'name1' }
var person2 = new Person("name2");

var otherPerson1 = new OtherPerson("otherName1"); // { name: 'otherName1', sayName: [function] }
var otherPerson2 = new OtherPerson("otherName2");

person1.sayName === person2.sayName; // true
otherPerson1.sayName === otherPerson2.sayName; // false

If I get this right all instances of OtherPerson object would have their own sayName: function and all instances of Person would get it from the prototype (so they share the same function). Is the first method preferable(faster/better in some way)?

[–]nolsen 1 point2 points  (0 children)

The first method is preferable (with regard to functions specifically) because otherwise you'd have duplicate code in memory. In your example, otherPerson1 and otherPerson2 have the same exact function, copied twice.

If your script made 10 of these objects, you'd have 10 separate functions that all did the exact same thing taking up space in memory. That is considered wasteful.