1function Product(name, price) {
2 this.name = name;
3 this.price = price;
4
5 if (price < 0)
6 throw RangeError('Cannot create product "' + name + '" with a negative price');
7 return this;
8}
9
10function Food(name, price) {
11 Product.call(this, name, price);
12 this.category = 'food';
13}
14Food.prototype = new Product();
15
16function Toy(name, price) {
17 Product.call(this, name, price);
18 this.category = 'toy';
19}
20Toy.prototype = new Product();
21
22var cheese = new Food('feta', 5);
23var fun = new Toy('robot', 40);
1// let us see what exactly CALL, BIND method in JS
2
3/* NOTE : (CALL , APPLY executes immediately) and
4(BOUND - it returns bounded function that execute later)
5
6NOTE : call will take its additinal arguments just like that
7 eg : XYZ.call(this , a , b , c);
8
9NOTE : apply will take its additinal arguments as an ARRAY
10 eg : XYZ.apply(this , [a , b , c])
11
12NOTE : All of them are for borrowing values(property and methods)
13 from another function
14*/
15
16/*CALL method {let's say we have constructor func}, we need all these
17properties and methods in another function, in that way CALL is
18highly useful */
19function Person(name,place){
20 this.name = name;
21 this.place = place;
22 this.greet = function(){
23 return (`HEllo I am ${this.name} comes from ${this.place}`);
24 }
25};
26
27//I need above func prop,methods in below, let's see how to get
28function Teacher(name,place,sub){
29 this.sub = sub;
30 //since i get name,place from Person function I no need to mention here
31 Person.call(this , name , place);
32 this.greeting = function(){
33 return(`I am ${name}, from ${place} and I teach ${this.sub}`);
34 }
35 /* also here, we don't need to mention (this.name / this.place) because,
36 we call them here and (this) referes to current Teacher context. try
37 inheriting below and check in console.
38 */
39}
40
41var Te1 = new Teacher("Ranjan" , "Salem" , "JavaScript");
42 Te1 // all prop and methods
43 Te1.name // Ranjan
44 Te1.place //Salem
45 Te1.greeting() // I am Ranjan, from Salem and I teach JavaScript
46
47
48
49
50// for BIND
51function Student(name,place,like){
52 this.like = like;
53 //since i get name,place from Person function I no need to mention here
54 Person.apply(this , [name , place]);
55 this.about_me = function(){
56 return(`My name is ${name}, I come from ${place} and I
57 like to play${this.like}`);
58 }
59}
60
61var Pe1 = new Student("Max" , "Mettur" , "Cricket");
62 Pe1 // all prop and methods
63 Pe1.name // Max
64 Pe1.place // Metttur
65 Pe1.about_me() // My name is Max, I come from Mettur and I like to play cricket