您的位置:首页 > Web前端 > JavaScript

面向对象的JavaScript-005-Function.prototype.call()的3种作用

2016-05-24 15:13 645 查看
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


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: