美文网首页
JS中call方法遇到的困惑

JS中call方法遇到的困惑

作者: 咸鱼而已 | 来源:发表于2016-11-18 15:21 被阅读13次

简单说一下call方法调用父类构造函数。

在一个子构造函数中,你可以通过调用父构造函数的call方法来实现继承,类似于Java中的写法。下例中,使用 Food 和 Toy 构造函数创建的对象实例都会拥有在 Product 构造函数中添加的 name 属性和 price 属性,但 category 属性是在各自的构造函数中定义的。

function Product(name, price) {
  this.name = name;
  this.price = price;

  if (price < 0) {
    throw RangeError('Cannot create product ' +
                      this.name + ' with a negative price');
  }

  return this;
}

function Food(name, price) {
  Product.call(this, name, price);  //穿进去三个参数,第一个this函数作为隐式参数传入
  this.category = 'food';
}

Food.prototype = Object.create(Product.prototype);
Food.prototype.constructor = Food; // Reset the constructor from Product to Food

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}

Toy.prototype = Object.create(Product.prototype);
Toy.prototype.constructor = Toy; // Reset the constructor from Product to Toy

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

相关文章

网友评论

      本文标题:JS中call方法遇到的困惑

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