Javascript call to chain constructors for an object

1) call

var obj = {num:2};

var add = function(a){
    return this.num + a;
};

add.call(obj, 1); //function.call(obj, arg)

2) a call to the designers of the chain for the object.

var Product = function (name, price) {
    this.name = name;
    this.price = price;
}

var Food = function(name, price) {
    Product.call(this, name, price); // <-- 1. Product is obj constructor not fun
                                     //     2. what is 'this' here?
    this.category = 'food';
}

var cheese = new Food('feta', 5);

console.dir(cheese);

I'm currently learning javascript oop, I found an example about Function.prototype.call()chain constructors , but I don't understand how this works.

1) not calling the function call invocation call obj? but Product is construct.

var food = { category : 'food' };

var Product = function (name, price) {
    this.name = name;
    this.price = price;
}

var cheese = Product.call(food);
console.dir(cheese);//this will become undefine

2) what is 'this'? Food facility? Product.call(new Food, name, price);?

* the end result var cheesewill be an object,Product.call(new Food obj, name, price)

The product is still a function, why does the result become an object?

+4
source share
1 answer

, , , new ( ). Food , new Food(...).

, new , this. . , return, , new: , this .

:

Product.call(this, name, price); // <-- 1. Product is construct not fun

:

new Product(name, price)

... . , new Food(...). this. new Product(...) ( ) (this). .call(), - , this .

, .call undefined, new, , . return, undefined. , , : this .

, Product, Food . Food new Food(), , instanceof Food.

, , , :

  • instanceof Product
  • , Product.prototype, , new Food().
+4

Source: https://habr.com/ru/post/1664980/


All Articles