Home > database >  Difference between two function placements
Difference between two function placements

Time:02-01

What would be the difference between the following two ways of attaching a method(?) to a parent function:

var Person = function(first, last) {
    this.first = first;
    this.last = last;
};
Person.prototype.personMethod = function() {
    // ...
};

And:

var Person = function(first, last) {
    this.first = first;
    this.last = last;
    this.personMethod = function() {
        // ...
    };
}

CodePudding user response:

In the first approach, the method is put onto the prototype. Every instance will share the same personMethod because every instance inherits from Person.prototype.

var Person = function(first, last) {
    this.first = first;
    this.last = last;
};
Person.prototype.personMethod = function() {
    // ...
};

const p1 = new Person();
const p2 = new Person();
console.log(p1.personMethod === p2.personMethod);
console.log(p1.hasOwnProperty('personMethod'));
console.log(Object.getPrototypeOf(p1).hasOwnProperty('personMethod'));
console.log(Object.getPrototypeOf(p1) === Person.prototype);

In the second approach, every instance has its own separate method, and it's not on the prototype.

var Person = function(first, last) {
    this.first = first;
    this.last = last;
    this.personMethod = function() {
        // ...
    };
}

const p1 = new Person();
const p2 = new Person();
console.log(p1.personMethod === p2.personMethod);
console.log(p1.hasOwnProperty('personMethod'));

In modern JavaScript, it's usually preferable to use a class instead, which puts methods onto the prototype.

class Person {
  constructor(first, last) {
    this.first = first;
    this.last = last;
  }
  personMethod(){}
};

const p1 = new Person();
const p2 = new Person();
console.log(p1.personMethod === p2.personMethod);
console.log(p1.hasOwnProperty('personMethod'));
console.log(Object.getPrototypeOf(p1).hasOwnProperty('personMethod'));
console.log(Object.getPrototypeOf(p1) === Person.prototype);

Assigning the function inside the constructor can be useful if you want the function to close over a variable only scoped to the constructor, which wouldn't work for methods if the variable isn't set to the instance.

var Person = function(first, last) {
    // say we don't want to assign these arguments to the instance
    // but we can still do
    this.getName = () => first   ' '   last;
}

const p = new Person('John', 'Doe');
console.log(p.getName());

  •  Tags:  
  • Related