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 Food(name, price) {
this.name = name;
this.price = price;
if (price < 0) {
throw RangeError('Cannot create product ' + this.name + ' with a negative price');
}
this.category = 'food';
}
//function Toy 同上
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
var animals = [{
species: 'Lion',
name: 'King'
},
{
species: 'Whale',
name: 'Fail'
}];
for (var i = 0; i < animals.length; i++) {
(function (i) {
console.log(animals[i]);
})(i)
}
//一次輸出兩個對象
for (var i = 0; i < animals.length; i++) {?
(function(i) {
console.log(('#' + i + ' ' + this.species + ': ' + this.name))
}).call(animals[i], i)
}
//使用call究抓,將animals[i]替代為匿名函數(shù)中this的值,同時傳入i作為參數(shù)