
正文
面向对象的JavaScript-005-Function.prototype.call()的3种作用
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
1.
// call的3种作用
// 1.Using call to chain constructors for an object
function Product(name, price) {
this.name = name;
this.price = price; if (price < 0) {
throw RangeError('Cannot create product ' +
this.name + ' with a negative price');
}
} function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
} function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
} var cheese = new Food('feta', 5);
console.log(cheese);
var fun = new Toy('robot', 40);
console.log(fun); // 2.Using call to invoke an anonymous function
var animals = [
{ species: 'Lion', name: 'King' },
{ species: 'Whale', name: 'Fail' }
]; for (var i = 0; i < animals.length; i++) {
(function(i) {
this.print = function() {
console.log('#' + i + ' ' + this.species
+ ': ' + this.name);
}
this.print();
}).call(animals[i], i);
} // Using call to invoke a function and specifying the context for 'this'
// In below example, when we will call greet the value of this will be bind to object i.
function greet() {
var reply = [this.person, 'Is An Awesome', this.role].join(' ');
console.log(reply);
} var i = {
person: 'Douglas Crockford', role: 'Javascript Developer'
}; greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer







