Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's a way of "borrowing" the constructor function of <code>Product</code> to initialize your new <code>Food</code>.</p> <p>When you call a function with <code>new</code>, you're setting <code>this</code> to be the new instance. You're then doing <code>Product.call</code> (i.e. calling the <code>Product</code> function and setting <code>this</code> inside the <code>Product</code> function to be your new <code>Food</code> instance (which is <code>this</code> inside <code>Food</code>)), and passing your <code>name</code> and <code>price</code>.</p> <p>After <code>Product.call(this, name, price);</code> you should find that <code>this.name</code> and <code>this.price</code> have been set.</p> <p>This doesn't allow inheritance, nor do you <em>gain</em> inheritance; it just executes the constructor function <code>Product</code> on your new <code>Food</code> instance. </p> <p>To gain inheritance, you'd also have to set the <code>prototype</code> of <code>Food</code> to be a new <code>Product</code> instance;</p> <pre><code>function Product(name, price) { this.name = name; this.price = price; } Product.prototype.showPriceIn = function (currency) { alert(this.price + currency); } function Food(name, price) { Product.call(this, name, price); this.category = 'food'; } Food.prototype = new Product; var chicken = new Food('chicken','40'); chicken.showPriceIn("$"); </code></pre> <p><a href="http://jsfiddle.net/hPWMN/" rel="nofollow">http://jsfiddle.net/hPWMN/</a></p> <hr> <p><strong>N.B:</strong> Be careful saying that "Bob is invoked with the <strong><em>scope</em></strong> of Alice"; this isn't true. Bob doesn't inherit the scope of Alice, the value of <code>this</code> inside the <code>greet</code> function is merely altered to be <code>Alice</code>. Inheriting the scope would imply Bob gains access to private variables and the like, which he doesn't.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload