面向对象的JavaScript-005-Function.prototype.call()的3种作用
1.
1 // call的3种作用 2 // 1.Using call to chain constructors for an object 3 function Product(name, price) { 4 this.name = name; 5 this.price = price; 6 7 if (price < 0) { 8 throw RangeError('Cannot create product ' + 9 this.name + ' with a negative price'); 10 } 11 } 12 13 function Food(name, price) { 14 Product.call(this, name, price); 15 this.category = 'food'; 16 } 17 18 function Toy(name, price) { 19 Product.call(this, name, price); 20 this.category = 'toy'; 21 } 22 23 var cheese = new Food('feta', 5); 24 console.log(cheese); 25 var fun = new Toy('robot', 40); 26 console.log(fun); 27 28 // 2.Using call to invoke an anonymous function 29 var animals = [ 30 { species: 'Lion', name: 'King' }, 31 { species: 'Whale', name: 'Fail' } 32 ]; 33 34 for (var i = 0; i < animals.length; i++) { 35 (function(i) { 36 this.print = function() { 37 console.log('#' + i + ' ' + this.species 38 + ': ' + this.name); 39 } 40 this.print(); 41 }).call(animals[i], i); 42 } 43 44 // Using call to invoke a function and specifying the context for 'this' 45 // In below example, when we will call greet the value of this will be bind to object i. 46 function greet() { 47 var reply = [this.person, 'Is An Awesome', this.role].join(' '); 48 console.log(reply); 49 } 50 51 var i = { 52 person: 'Douglas Crockford', role: 'Javascript Developer' 53 }; 54 55 greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer
You can do anything you set your mind to, man!