S
S
Stepan2014-08-03 22:31:13
JavaScript
Stepan, 2014-08-03 22:31:13

How to deal with the prototype and the constructor?

Please help me understand this code. I think I don't understand something.
The prototype property is an intermediate object. Explain line by line please

function extend(Child, Parent) {
  var F = function() { }
  F.prototype = Parent.prototype
  Child.prototype = new F()
  Child.prototype.constructor = Child
  Child.superclass = Parent.prototype
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Petrov, 2014-08-03
@Petroveg

var F = function() { }
F.prototype = Parent.prototype
Child.prototype = new F()

We create an intermediate auxiliary constructor, which is needed in order not to drag all the tricky things from creating an object using the Parent constructor directly. We don't know what own properties are set when the constructor is called, do we?
With such a call, you can pick up the devil knows what.
Updated the reference to the constructor in the prototype. For what? Apparently in order for the lines to have the same effect:
var iLoveToMakeChild1 = Object.create(Child.prototype)
var iLoveToMakeChild2 = new Child()

And just in case, we put a reference to the prototype of our ancestor in the constructor property. It is very necessary.
Your example is a typical inheritance pattern.
What to read:
dmitrysoshnikov.com/ecmascript/ru-javascript-the-core
habrahabr.ru/post/120193
habrahabr.ru/post/108915
Update:
I'm not sure this explanation will really explain, but...
05c7add10c82486b89a0109e62db1c7f.png
function Млекопитающее() {
  //И вот тут может произойти непонятное без прокладки F
}
Млекопитающее.prototype.commonParams = [
  'Вскармливает детей молоком',
  'Теплокровное'
];

function Человек(options) {
  if (options && typeof options == 'object') {
    for (var i in options) {
      this[i] = options[i];
    }
  }
}

function Кошка(options) {
  if (options && typeof options == 'object') {
    for (var i in options) {
      this[i] = options[i];
    }
  }
}

function extend(Child, Parent) {
  var F = function() { };
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.prototype.constructor = Child;
  Child.superclass = Parent.prototype;
}

extend(Человек, Млекопитающее);
Человек.prototype.ownParams = [
  'Носит одежду',
  'Поёт в караоке'
];

extend(Кошка, Млекопитающее);
Кошка.prototype.ownParams = [
  'Забавно урчит',
  'Ест мух'
];

var man1 = new Человек({
    name: 'Петя',
    params: [
      'Брюнет',
      'Любит Хауса',
      'Бросил курить'
    ]
  }),
  animal1 = new Кошка({
    name: 'Маська',
    params: [
      'Любит кукурузу',
      'Имеет 2 лотка'
    ]
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question