JavaScript - call () method

function Product(name, price) {
  this.name = name;
  this.price = 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);
var fun = new Toy('robot', 40);

1, using the  call method calls the parent constructor

       In a sub-constructor, you can call the parent constructor  call to implement inherited methods, similar  Java in wording. In the following example, the use  Food and the  Toy constructor creates an object instance will have the  Product added constructor  name attributes and  price properties, but the  category properties are defined in the respective constructor.

2, Grammar

fun.call(thisArg, arg1, arg2, ...)

1) Parameters:

thisArg

     In the  fun specified function runtime  this values . IF (thisArg == undefined | null) = the this window , IF (thisArg Number The == | boolean | String) the this new new Number The == () | new new Boolean () | new new String ()

arg1, arg2, ...

     Specifies the list of parameters.

2) Return value:

     Use caller-provided  this values and parameters call the function's return value. If the method does not return value is returned  undefined.

3) Description:

call() Allow for different objects belonging to one object allocation and call the function / method.

call() Provide new  this  value to the function / method of the current call. You can use  call to implement inheritance: write a method, and then let the other new objects to inherit it (but not write again this method in the new object).

 

Guess you like

Origin www.cnblogs.com/sylys/p/11641528.html