T
T
TrainHard2015-09-27 17:26:38
JavaScript
TrainHard, 2015-09-27 17:26:38

What are the differences between these constructs in JavaScript?

Hi all!
Please explain, please.
There are such constructions:

function Person (name, age) {
  this.name = name;
  this.age = age;
  this.getName = getName;
}

function getName() {
    return this.name;
};

var Mike = new Person('Mike', 24);
var John = new Person('John', 30);

Mike.getName === John.getName;// true

and this one:
function Person (name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.getName = function () {
    return this.name;
};

var Mike = new Person('Mike', 24);
var John = new Person('John', 30);

Mike.getName === John.getName;// и здесь true

If the objects refer to the same function and evaluate to true when compared, does it make sense to use the prototype property , is there a difference in constructions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Inchin ☢, 2015-09-27
@TrainHard

1) Everything should be in its place, sorted out, this is the basis of the JavaScript code. This is justified by the fact that several people can work on the code, and if everyone has their own mess, then in the end someone can do this:

function getName(){...} //вы объявили функцию
//code
//code
function getName(){..} //Еще какой-то господин объявил функцию
//Что в итоге? -Объявлена будет вторая.

2) It is customary to put static properties of an object into its prototype, since creating many objects with an identical getName method is stupid, only memory is wasted.
And if it is similar to the first option, then like this:
function Person (name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.getName = getName;

function getName() {
    return this.name;
};

var Mike = new Person('Mike', 24);
var John = new Person('John', 30);

Mike.getName === John.getName;// true

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question