I have seen this code on the MDN site:
01 function Product(name, value){
02 this.name = name;
03 if(value >= 1000)
04 this.value = 999;
05 else
06 this.value = value;
07 }
08
09 function Prod_dept(name, value, dept){
10 this.dept = dept;
11 Product.call(this, name, value);
12 }
13
14 Prod_dept.prototype = new Product();
15
16 // since 5 is less than 1000, value is set
17 cheese = new Prod_dept("feta", 5, "food");
18
19 // since 5000 is above 1000, value will be 999
20 car = new Prod_dept("honda", 5000, "auto");
It says you can use call to chain constructors. I have some questions:
1) Why is line 14 called why would we add it to the prototype and why would that mean that Product is called when we create Prod_dept?
2) What does line 11 mean? How is this related to the prototype?
3) What is line 20 meant to show us?
1) Setting an instance of Product
as the prototype object for Prod_dept
adds the values and methods of that Product
instance (and its prototype) to the prototype chain of all your Prod_dept
instances.
It also allows instanceof
to show that an object created from Product_dept
is an instance of both constructors
var a = new Product();
var b = new Product_dept();
a instanceof Product // true
a instanceof Product_dept // false
b instanceof Product // true
b instanceof Product_dept // true
2) Because this
is the new object being constructed by Prod_dept
, the .call
lets you set that object as the this
value of the Product
method, so that whatever the Product
method does with this
will be done on that new Prod_dept
instance (in this case, running the code for adding values to name
and value
properties).
3) It just creates a new instance from the Prod_dept
constructor.
Overall, this is one pattern for using JavaScript's prototypal inheritance mechanism.
The code is simply demonstrating prototypal inheritance in JavaScript.
1) What the code is saying on line 14 is that you want your Prod_dept
Function to inherit the properties and characteristics of the base Product
Function.
Every function in JavaScript has a prototype property and it contains an object that you can add methods and properties to.
Prototype is a special property that gets created as soon as you define the function. Its initial value is an empty object {} but can be overwritten to allow you to define your own methods or inherit those from another Function.
2) Line 10 is simply assigning a property to your Prod_dept
Function the value being provided by the dept argument being passed through the constructor.
3) Line 14 is allowing you to apply the other two arguments "name, value" to your base Product
function but in the context of your Prod_dept
Function. Further information on that method can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With