美文网首页前端文档记录
2017-0409-原型和call()-2

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

作者: Exap | 来源:发表于2017-04-09 22:08 被阅读0次

    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作为参数

    相关文章

      网友评论

        本文标题:2017-0409-原型和call()-2

        本文链接:https://www.haomeiwen.com/subject/yljjattx.html