2017-0409-原型和call()-2

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]替代为匿名函数中this的值,同时传入i作为参数

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容