Content: Prototype inheritance, constructor borrowing inheritance, introduction to strict mode, using call and apply, combination inheritance.
Prototype Inheritance
Inheritance, in essence, is about code reuse.
Disadvantages:
- There’s no way to assign values to inherited properties.
- Inherited reference type data is shared among all instances.
1 | // Define the Animal constructor |
Demonstrating the disadvantages of prototype inheritance:
1 | function Person(name, favour) { |
To address these issues, we can use constructor borrowing inheritance.
Constructor Borrowing Inheritance
Disadvantage: Constructor borrowing inheritance cannot inherit members from the parent constructor’s prototype.
1 | function Person(name, favour) { |
Strict Mode
In non-strict mode, the this keyword in regular functions refers to the window object. In strict mode, the this keyword in regular functions is undefined.
Strict mode is enabled by writing "use strict" within a function.
1 | // Non-strict mode |
Call and Apply
- Can be used to invoke functions.
- Can change the
thiscontext within the function. - Can convert array-like objects.
- Can borrow methods from other objects.
- If there’s a first argument, it must be of reference type.
1 | function foo(a, b) { |
Changing this context using call and apply:
1 | // Changing the 'this' context within a regular function |
Converting array-like objects:
1 | // 1. Using 'slice' and 'call' |
Borrowing methods from other objects:
1 | var arr = [12321, 234, 99999999, 4454, 12, 454545, 343, 34, 342]; |
Bind (ES5 Feature, Function Currying)
The first argument must be of reference type.
bind changes the this context within a function but doesn’t invoke it. It returns a new function with the specified this context.
1 | function foo(a, b) { |
Changing the this context within a timer function:
1 | var inner = function () { |
Combination Inheritance
Combination inheritance combines prototype inheritance and constructor borrowing inheritance.
1 | // Define a Person |